基于文件名开头的Powershell脚本删除文件

问题描述 投票:1回答:3

所以我在以]开头的文件夹中有文件>

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

使用-File-Directory限制Get-ChildItem仅输出该类型的项目。

  • Get-ChildItem与PowerShell -Include结合使用,以限制对名称以wildcard expression0__开头的文件的匹配。
  • 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 ]。

  • $true运算符支持与10参数相同的通配符模式,但请注意,后者的-like参数-更快-仅支持不同的,功能较弱的模式-请参见Get-ChildItem
  • 请找到用于确切预期输出的脚本。也不要忘记将其标记为答案。用原始路径替换路径

-Include
powershell glob get-childitem
3个回答
0
投票

0
投票

使用-File-Directory限制Get-ChildItem仅输出该类型的项目。


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.