在powershell中编写以下脚本,可以自动删除指定路径下指定日期前的文件。
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$path,
[Parameter(Position=1,Mandatory=$true)]
[int]$daysToKeep
)
if(-Not (Test-Path -Path $path)){
Write-Warning "The path '$path' does not exist."
return
}
$currentDate = Get-Date
$maxDate = $currentDate.AddDays(-$daysToKeep)
Get-ChildItem -Path $path | Where-Object { $_.LastWriteTime -lt $maxDate } | Remove-Item -Force
代码注释:
使用时,可以在powershell中运行此脚本,并传递路径和删除天数
.\deleteOldFiles.ps1 -path "C:\temp" -daysToKeep 30
上面的命令将删除"C:\temp"下超过30天的文件。