powershell - 列出目录中超过一定年龄的项目,然后将其删除
问题描述
我确定我错过了一些明显的东西,但是自从我需要使用 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
但这所做的只是列出项目,而不是删除它们。
解决方案
推荐阅读
- r - doParallel 和 foreach 的问题。我可以注册核心,但它们似乎没有运行
- ubuntu - 无法在 UBuntu 18.04 上安装 .Net Core 2.2
- r - gsub 错误地识别 [:cntrl:] 字符
- javascript - 如何制作一个加载栏,每次加载图片时更新并添加百分比
- c# - 改进代码,添加 Goto 或循环功能
- c# - 使用 C# 和 Unity 在一个循环中连续移动“播放器”
- symbolic-math - 如何在 KLEE 中找到路径条件?理想情况下,如何找到最长/最短路径的路径条件
- selenium - 詹金斯奴隶没有在 GUI 中访问 chrome
- c - 在 C 中使用 system()、fgets 和 sprintf 将文本附加到文件时出现问题
- c# - 增加单核 CPU 使用率