我只想删除一个特定文件夹中超过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天的文件。
$Path = 'C:\Temp'
$Daysback = "-15"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
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
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse
这将删除旧文件夹和它的内容。
另一种方法是从当前日期减去15天,并将CreationTime与该值进行比较:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
如果你在Windows 10系统上使用上述示例有问题,请尝试将. creationtime替换为. lastwritetime。这对我很管用。
dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force
推荐文章
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符
- 使用PowerShell删除超过15天的文件
- 数组添加 vs +=
- PowerShell中用户输入的提示符
- 如何从字符串执行任意本机命令?
- 如何使用。net 4运行时运行PowerShell ?
- 在PowerShell中重新加载路径
- 函数在PowerShell中的返回值
- 如何在PowerShell中输出一些东西
- 调用webrequest, POST参数
- 无法加载.ps1,因为在此系统上禁止执行脚本
- 如何获得正在执行的cmdlet的当前目录
- 如何从批处理文件运行PowerShell脚本
- 如何从PowerShell中的外部进程捕获输出到变量?