我只想删除一个特定文件夹中超过15天前创建的文件。我如何使用PowerShell做到这一点?
当前回答
另一种方法是从当前日期减去15天,并将CreationTime与该值进行比较:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
其他回答
另一种方法是从当前日期减去15天,并将CreationTime与该值进行比较:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
基本上,迭代给定路径下的文件,从当前时间中减去每个文件的CreationTime,并与结果的Days属性进行比较。-WhatIf开关会告诉你在不删除文件的情况下会发生什么(哪些文件将被删除),删除开关来实际删除文件:
$old = 15
$now = Get-Date
Get-ChildItem $path -Recurse |
Where-Object {-not $_.PSIsContainer -and $now.Subtract($_.CreationTime).Days -gt $old } |
Remove-Item -WhatIf
Esperento57脚本在较旧的PowerShell版本中无法运行。这个例子是:
Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
另一种选择(15。自动输入[timespan]):
ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose
给出的答案将只删除文件(无可否认,这是本文标题中的内容),但这里有一些代码将首先删除所有超过15天的文件,然后递归删除可能遗留的任何空目录。我的代码还使用-Force选项删除隐藏和只读文件。另外,我选择不使用别名,因为OP对PowerShell来说是新的,可能不理解gci、?、%等是什么。
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
当然,如果您想在实际删除它们之前查看哪些文件/文件夹将被删除,您只需在两行末尾的Remove-Item cmdlet调用中添加-WhatIf开关。
如果你只想删除15天内没有更新的文件,而不是15天前创建的文件,那么你可以使用$_。LastWriteTime而不是$_.CreationTime。
这里显示的代码与PowerShell v2.0兼容,但我也在我的博客上将此代码和更快的PowerShell v3.0代码作为方便的可重用函数展示。
推荐文章
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 是否有一种方法可以通过双击.ps1文件来使PowerShell脚本工作?
- PowerShell等价于grep -f
- “Write-Host”,“Write-Output”,或“[console]::WriteLine”之间的区别是什么?
- Powershell相当于bash的&号(&),用于分叉/运行后台进程
- PowerShell脚本在机器上返回。net框架的版本?
- 如何在PowerShell中获得MD5校验和
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符
- 使用PowerShell删除超过15天的文件
- 数组添加 vs +=
- PowerShell中用户输入的提示符
- 如何从字符串执行任意本机命令?
- 如何使用。net 4运行时运行PowerShell ?