Powershell根据日期范围条件删除文件夹文件
在下面的命令中,删除超过30天的文件Powershell根据日期范围条件删除文件夹文件,powershell,Powershell,在下面的命令中,删除超过30天的文件 Get-ChildItem –Path "C:\path\to\folder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item 但是如何添加过滤器,如果 date is 1st of each month or date is 15th of each month or date is 30 also ignor
Get-ChildItem –Path "C:\path\to\folder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item
但是如何添加过滤器,如果
date is 1st of each month or
date is 15th of each month or
date is 30
also ignore files with name '%weekly%'
您可以使用下面的powershell脚本:
$FolderName=“c:\dev\test”
foreach($file-in(GEt-childitem-Path$FolderName-Recurse | Where对象{($\.LastWriteTime-lt(GEt-Date.AddDays(-30)))
{
如果($file.lastwritetime.Date.Day-in 1,15,30)-或($file-like'*weekly*'))
{
持续
}
删除项-路径$file.FullName
}
您可以使用下面的powershell脚本:
$FolderName=“c:\dev\test”
foreach($file-in(GEt-childitem-Path$FolderName-Recurse | Where对象{($\.LastWriteTime-lt(GEt-Date.AddDays(-30)))
{
如果($file.lastwritetime.Date.Day-in 1,15,30)-或($file-like'*weekly*'))
{
持续
}
删除项-路径$file.FullName
}
由于您只想删除文件,因此应使用获取子项
上的-File
开关。
为了不继续计算30天前的参考日期,我想首先在变量$refDate
中定义它。
此外,还应通过将时间部分设置为00:00:00
来使用从午夜开始的日期。这就是属性Date
的作用
$refDate = (Get-Date).AddDays(-30).Date # set it to midnight
Get-ChildItem -Path "C:\path\to\folder" -File -Recurse |
Where-Object { ($_.LastWriteTime -lt $refDate) -and
($_.BaseName -notlike '*%weekly%*') -and
(1,15,30 -notcontains $_.LastWriteTime.Day)} |
Remove-Item -WhatIf
另外,我添加了
-WhatIf
开关,因此您可以看到首先会发生什么。如果您对控制台中的消息感到满意,请删除此开关以实际开始删除文件,因为您只想删除文件,因此应使用获取子项
上的-File
开关。
为了不继续计算30天前的参考日期,我想首先在变量$refDate
中定义它。
此外,还应通过将时间部分设置为00:00:00
来使用从午夜开始的日期。这就是属性Date
的作用
$refDate = (Get-Date).AddDays(-30).Date # set it to midnight
Get-ChildItem -Path "C:\path\to\folder" -File -Recurse |
Where-Object { ($_.LastWriteTime -lt $refDate) -and
($_.BaseName -notlike '*%weekly%*') -and
(1,15,30 -notcontains $_.LastWriteTime.Day)} |
Remove-Item -WhatIf
另外,我添加了-WhatIf
开关,因此您可以看到首先会发生什么。如果您对控制台中的消息感到满意,请删除此开关以实际开始删除文件