[英]Filter and delete files and folders(and files inside of folders) older than x days in powershell
[英]Powershell script to delete files older than x days, but not folders
我有一个我认为可以正常运行的脚本,但是我得到的报告是它正在删除文件夹而不只是文件。 有人可以帮我调整我的脚本来解决这个问题吗? 我是否需要添加-file过滤器?
$Path = "D:\AppData\Downloads"
$Limit = (Get-Date).AddDays(-6)
Get-ChildItem -path $Path -Recurse -force | Where-Object {!$_.PSIsContainer -and $_.CreationTime -lt $Limit } | Remove-Item -recurse -Force
您的Where-Object子句很可能无法正常工作。
{!$_.PSIsContainer -and $_.CreationTime -lt $Limit }
应该
{!$_.PSIsContainer -and ($_.CreationTime -lt $Limit)}
括号可确保独立评估第二个逻辑比较。 有关更多信息,请参见about_logical_operators
Windows PowerShell逻辑运算符仅评估确定该语句真值所需的语句。 如果包含and运算符的语句中的左操作数为FALSE,则不评估右操作数。 如果包含or语句的语句中的左操作数为TRUE,则不计算右操作数。 如此一来,您可以以与使用If语句相同的方式使用这些语句。
另外,由于它正在删除文件而不是文件夹,因此-Recurse
for Remove-Item
似乎不必要。 从Alroc注释:假设你有3版或以上的PowerShell您可以使用简化此-File
的参数Get-ChildItem
到位的!$_.PSIsContainer
您的从句Where-Object
(这是被普遍在版本2中完成。)就像您的评论中所述:
Get-ChildItem -path $Path -file -Recurse -force | Where-Object {$_.CreationTime -lt $Limit }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.