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

时间:2013-12-05 15:45:36

标签: powershell arguments powershell-v2.0 powershell-v3.0

我使用的脚本删除超过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下运行脚本,而无需更改此文件中的任何内容。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您需要开始在脚本中使用参数:

http://technet.microsoft.com/en-us/magazine/jj554301.aspx