所以我在以]开头的文件夹中有文件>
1__
和
0__
示例文件
1__shal1absahal9182skab.php
0__abns1a3bshal54a4m5sb.php
我试图让我的Powershell脚本仅删除早于1__
的60 mins
文件,而0__
可以每360 mins
删除。
这是我当前的代码
$limit = (Get-Date).AddMinutes(-360)
$path = "C:\cache"
# 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
我的脚本当前将两个文件视为相同,并在360 minute
动机中将它们都删除。
所以我在以1__和0__开头的文件夹中有文件,例如1__shal1absahal9182skab.php 0__abns1a3bshal54a4m5sb.php。
[使用if和else与某些正则表达式模式匹配找到了一个解决方案。
$limit_guest = (Get-Date).AddMinutes(-360) #6 hours
$limit_logged_in = (Get-Date).AddMinutes(-60) #1 hours
$path = "C:\cache"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { if ( $_ -match "^0__.*" ) { !$_.PSIsContainer -and $_.CreationTime -lt $limit_guest } else { !$_.PSIsContainer -and $_.CreationTime -lt $limit_logged_in } } | 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
您可以如下简化your own solution:
- 将
Get-ChildItem
与PowerShell -Include
结合使用,以限制对名称以wildcard expression或0__
开头的文件的匹配。 1__
注:
previews
以上命令中的$now = Get-Date
$limit_guest = $now.AddMinutes(-360) #6 hours
$limit_logged_in = $now.AddMinutes(-60) #1 hour
# Delete files older than the $limit.
Get-ChildItem -File -Path $path -Recurse -Force -Include '[01]__*' |
Where-Object {
$_.CreationTime -lt ($limit_guest, $limit_logged_in)[$_.Name -like '1__*']
} | Remove-Item -Force -WhatIf
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Directory -Path $path -Recurse -Force |
Where-Object {
(Get-ChildItem -File -LiteralPath $_.FullName -Recurse -Force).Count -eq 0
} | Remove-Item -Force -Recurse -WhatIf
。确定要执行的操作后,请除去-WhatIf
common parameter。
注意:-WhatIf
通过基于条件-WhatIf
选择($limit_guest, $limit_logged_in)[$_.Name -like '1__*']
值之一来模拟三元条件:如果条件的计算结果为$limit_*
,则将其解释为数组索引$_.Name -like '1__*'
,否则将其解释为[C0 ]。
-Include