簡體   English   中英

Powershell 如何從刪除過程中排除文件夾

[英]Powershell how to exclude folders from deletion process

我有一個 PowerShell 腳本,用於從 Windows 機器中刪除所有類型的文件,這些文件從根文件夾及其子文件夾中超過 x 天。 這工作正常,但是現在我想從刪除過程中排除 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開關,而不必在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM