我写了一个Powershell脚本,应该删除超过25天的子目录中的文件。
# # Variables. # $days = 25 $src = "C:\Users\ArifSohM\Desktop\TestFolder\" # Check if files are older than 25 days. Get-childitem -path $src | ForEach-Object { $age = New-Timespan ($_.LastWriteTime) $(get-date) if($age.days -gt $days) { Remove-Item $_.FullName -force Write-host "$_ is older than 25 days and has been deleted." -ForegroundColor yellow } } #
这工作部分好,但是当我运行这个命令它也删除根目录中的文件。 这是我的文件夹结构:
所以,我想删除Directory1和Directory2所有内容,但不是在Test Folder 。 可以这样做吗?
这可以通过使用Get-ChildItem -Directoryselect仅目录以及通过它们循环来完成(以及其他方式)。
请注意,您的/我的function将不处理子文件夹内的子文件夹。 这只是对原始脚本的简单调整。
$days = 25 $src = "C:\Users\ArifSohM\Desktop\TestFolder\" # Check if files are older than 25 days. $dirs = Get-childitem -path $src* -Directory foreach ($dir in $dirs) { Get-childitem -path $dir | ForEach-Object { $age = New-Timespan ($_.LastWriteTime) $(get-date) if($age.days -gt $days) { Remove-Item $_.FullName -force Write-host "$_ is older than 25 days and has been deleted." -ForegroundColor yellow } } }