我有一个 PowerShell 脚本,用于从根文件夹及其子文件夹中删除超过 x 天的 Windows 计算机中的所有类型的文件。这工作正常,但是现在我想从删除过程中排除 2 个子文件夹。尝试过排除命令,但由于我不熟悉 Powershell,我正在努力使其正确。
PowerShell version: 5.1
文件夹结构(想从删除过程中排除 SubDir 2 和 SubDir3)
MainDir
|
SubDir1 -> Folder1 -> Folder2 -> Zip/CSV files
SubDir2 -> Folder1 ->.txt files
|
Folder2 -> .txt files
SubDir3 -> Zip files
SubDir4 -> Folder1 -> zip/csv files
脚本:
param([string] $dir = "C:\MainDir",
[string] $days = "15")
$error.clear()
try
{
$refDate = (Get-Date).AddDays(-$days)
Get-ChildItem -Path $dir -Recurse |
Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $refDate } |
Remove-Item -Force
}
catch {
Write-Error $_
}
if (!$error) {
Write-Host 'Data deleted for files which are older than' $days 'Days'
}
由于您使用的是 PS 5.1,您可以使用-File
switch 而不必!$_.PSIsContainer
在 Where 子句中使用。
要排除子文件夹,您可以尝试以下代码:
$refDate = (Get-Date).AddDays(-$days).Date # set to midnight
$excludeFolders = 'SubDir2', 'SubDir3' # an array of folder names to exclude
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($excludeFolders | ForEach-Object { [Regex]::Escape($_) }) -join '|'
Get-ChildItem -Path $dir -Recurse -File |
Where-Object { $_.DirectoryName -notmatch $notThese -and $_.LastWriteTime -lt $refDate } |
Remove-Item -Force
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句