我想写一个PowerShell脚本,用于使用记事本自动删除文件夹,我还想向该脚本添加2个参数。每当我运行这个脚本时,它都会询问文件的路径和天数。
Param1 - location of the folder
Param2 - no. Of days to keep
$param1 = Read-Host -Prompt 'location of the folder'
$param2 = Read-Host -Prompt 'no. of days to keep'
Get-ChildItem $param1 -recurse |
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays($param2)} |
Remove-Item
是否有在PowerShell脚本中传递参数的解决方案?在我的代码中,param1正在接受输入,但param2没有接受任何输入。
首先-请正确命名参数-更容易阅读。:(
第二,如果你想要比x更老的,你必须.AddDays(-$days)
。
所以它可能看起来像这样:
$path = Read-Host -Prompt 'location of the folder'
$days = Read-Host -Prompt 'no. of days to keep'
Get-ChildItem $path -Recurse |
#Mind the -$days (so we are looking for older than (today - X days)
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } |
Remove-Item #-WhatIf #for testing
这个概念与Grzegorz的有用答案相同,我只是添加了一些输入验证和错误处理。
$ErrorActionPreference = 'Stop'
$param1Block = {
try
{
[validatescript({Test-Path $_})]$z = Read-Host -Prompt 'location of the folder'
$z
}
catch
{
Write-Warning 'Invalid Path, try again.'
& $param1Block
}
}
$param2Block = {
try
{
[int](Read-Host -Prompt 'no. of days to keep')
}
catch
{
Write-Warning 'Only integers accepted, try again.'
& $param2Block
}
}
$param1 = & $param1Block
$param2 = & $param2Block
if([math]::Sign($param2) -ne -1)
{
$param2 = -$param2
}
Get-ChildItem $param1 -Recurse |
Where-Object -Property LastWriteTime -LT ([datetime]::Now).AddDays($param2) |
Remove-Item