Powershell:如何删除早于 X 天的特定格式文件(仅限 .xlsx)

Powershell : How to delete specific format file (.xlsx only) older than X days

我目前是 PowerShell 的新手,我想使用 Powershell 删除 .xlsx 早于 X 天的文件。 我在下面试过

Get-ChildItem D:\temp | ? { $_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf

但是上面的命令删除了我所有的数据(包括C盘数据)

请建议修改或新命令。提前致谢。

您似乎没有在代码中过滤 xlsx 文件。 xlsx 文件不是文件夹,因此我已从您的过滤器中删除了该条件。 $timelimit 未在显示的代码中定义,但需要是 dateTime 类型才能启用比较

Get-ChildItem d:\temp -filter "*.xlsx"| ? { $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf

这应该可以解决问题:

$timeLimit = 60 # Days
Get-ChildItem -Path "D:\temp" -Recurse -Include *.xlsx | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-$timeLimit)} | Remove-Item -WhatIf

如果这输出了预期的结果,您可以移除 -WhatIf 开关并试一试。