我认为这符合您的需求,我向您介绍了一些您可能不知道的概念,例如cmdletbinding,它允许您使用 -whatif 参数来干运行脚本。您还可以提供 -verbose 以查看沿途发生的情况,此时您还可以使用Add-Content cmdlet 附加到日志。
所以你可以这样运行它:
.\DeleteOldFiles.ps1 -Path c:\test -Age 50 -WhatIf -Verbose
然后,当您准备好删除文件时,您可以在没有 -WhatIf 参数的情况下运行它:
.\DeleteOldFiles.ps1 -Path c:\test -Age 50 -Verbose
这并不能回答您的所有问题,但应该可以帮助您入门,我在代码中添加了大量注释,因此您应该能够全部遵循。
# Add CmdletBinding to support -Verbose and -WhatIf
[CmdletBinding(SupportsShouldProcess=$True)]
param
(
# Mandatory parameter including a test that the folder exists
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType 'Container'})]
[string]
$Path,
# Optional parameter with a default of 60
[int]
$Age = 60
)
# Identify the items, and loop around each one
Get-ChildItem -Path $Path | where {$_.lastWriteTime -lt (Get-Date).addDays(-$Age)} | ForEach-Object {
# display what is happening
Write-Verbose "Deleting $_ [$($_.lastWriteTime)]"
# delete the item (whatif will do a dry run)
$_ | Remove-Item
}