首页 > 解决方案 > 列出目录中超过一定年龄的项目,然后将其删除

问题描述

我确定我错过了一些明显的东西,但是自从我需要使用 PowerShell 已经有一段时间了(注意它是第 2 版)。

我需要一个基本脚本来删除超过一定期限(3 天)的文件。我有以下内容:

$logDirectory = "C:\logs\"

$days = (Get-Date).AddDays(-3)

# Delete files older than the $days
Get-ChildItem -Path $logDirectory -Recurse | 
    Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $days } |
    %{Write-Host File Found: $_.fullname $_.LastWriteTime}

Get-ChildItem -Path $logDirectory -Recurse | 
    Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $days } |
    Remove-Item -Force 

这行得通,但如果我将两者结合起来,它就不行了。而且我确信必须有一种更简洁的方法来做到这一点,我可以写出文件列表,然后删除它们。就像是:

Get-ChildItem -Path $logDirectory -Recurse | 
    Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $days } |
    %{Write-Host File Found: $_.fullname $_.LastWriteTime} |
    Remove-Item -Force 

但这所做的只是列出项目,而不是删除它们。

标签: powershellpowershell-2.0

解决方案


推荐阅读