Powershell如何从删除过程中排除文件夹
我有一个PowerShell脚本,用于从根文件夹及其子文件夹中删除Windows计算机上超过x天的所有类型的文件。这很好,但是现在我想从删除过程中排除2个子文件夹。尝试了Exclude命令,但由于我不熟悉Powershell,因此我正在努力使其正确Powershell如何从删除过程中排除文件夹,powershell,Powershell,我有一个PowerShell脚本,用于从根文件夹及其子文件夹中删除Windows计算机上超过x天的所有类型的文件。这很好,但是现在我想从删除过程中排除2个子文件夹。尝试了Exclude命令,但由于我不熟悉Powershell,因此我正在努力使其正确 PowerShell version: 5.1 文件夹结构(要从删除过程中排除子目录2和子目录3) 脚本: param([string] $dir = "C:\MainDir", [string] $days = "15")
PowerShell version: 5.1
文件夹结构(要从删除过程中排除子目录2和子目录3)
脚本:
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
开关,而不必使用!$\。Where子句中的PSIsContainer
要排除子文件夹,可以尝试以下代码:
$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
$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