gpt4 book ai didi

powershell - 使用参数不在脚本文件中的Powershell

转载 作者:行者123 更新时间:2023-12-03 01:19:01 24 4
gpt4 key购买 nike

我正在使用一个脚本删除超过X天的文件。现在,我将变量直接放入脚本中。
由于我还是PowerShell的新手,所以我只知道有一种方法可以将变量放入另一个文件,然后让脚本“加载”它们。

现在我有这样的:

#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "5"
#----- define folder where files are located ----#
$TargetFolder = "C:\www\data"
#----- define extension ----#
$Extension = "*.zip"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)

#----- get files based on lastwrite filter and specified folder ---#

"Script Exection Modes"

"1 - Display all Configurations that are older than $Days days!"
"2 - Delete all Configurations that are older than $Days days!"

$mode = Read-Host "Please select mode"


if ($mode -eq 1)

{$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"} | where {$_.name -ne "configuration.zip"}

foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host $File.FullName -foregroundcolor "green"
}
else
{
Write-Host "No configurations found that are older than $Days days" -foregroundcolor "Green"
}
}
}

if ($mode -eq 2)

{$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"} | where {$_.name -ne "configuration.zip"}

foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "Red"
Remove-Item $File.FullName -Whatif
}
else
{
Write-Host "Deletion complete" -foregroundcolor "Green"
}
}
}

我希望变量 $days和模式选择移到另一个文件。因此您可以在模式1或模式2下运行脚本,而无需更改此文件中的任何内容。

最佳答案

您可以通过在脚本中添加参数来实现。

一个示例是将其添加到脚本文件的开头:

Param(
[int]$days,
[int]$mode
)

并注释掉选择模式和日期的行:
#$mode = Read-Host "Please select mode"
#$Days = "5"

然后像这样调用您的脚本
PS> test.ps1 5 1

有关更多信息,请参见此文章:
http://technet.microsoft.com/en-us/magazine/jj554301.aspx

关于powershell - 使用参数不在脚本文件中的Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com