Yinelemeli silme için Powershell Script

Sep 21 2020

Yeni bir işe başladım ve neredeyse anında Powershell yapmaya başladım, ancak Powershell'i yalnızca Exchange'de kullandım ve bu konuda çok basit.

Önümüzdeki birkaç ay boyunca daha fazla şey öğreneceğim, ancak şimdilik rastgele bir klasöre gidecek, her klasörü ve alt klasörü özyinelemeli olarak kontrol edecek, 2 günden eski dosyaları silen bir betiğe ihtiyacım var.

Biri bu konuda yeni başlayan birine yardım edebilir mi lütfen? '

Function DelFiles($RootFolder,[ref]$blnDeleteErrmsgSent){
  $blnDeleteErrmsgSent = $false
  $date = Get-Date $Folders              = Dir
  $FolderPath = "path" $PSEmailServer        = "servername"

  # Delete Old Files
  Cd $RootFolder foreach($folder in $Folders){ Cd $Folder.FullName
    $ToDelete = Dir -Attributes !readonly |Where {$_.lastwritetime -lt ((Get-Date).Adddays(-2))}
    foreach($File in $ToDelete){
      try{
        if($file.Attributes -notcontains "Directory"){ Remove-Item -Path $File.FullName -Force -ErrorAction Stop}
      }catch{
        # Only Send e-mail alert if we haven't already done so i.e. only once
        if(!($blnDeleteErrmsgSent.value)){ $errordescription=$_ $errorline=$_.InvocationInfo.Line.ToString() # Capture Error Information # Notify IT that this script has encountered an error Send-MailMessage -From "ScanDeletion@****.co.uk" -To "IT@****.co.uk" -Subject "errored while deleting old scan files" -Body ("The error occured at " + [string]$date +"`n Error:"+ $errordescription +"`n Line:"+ $errorline)

            # Set Flag to True so we don't send multiple e-mail alerts for file deletion errors.
            $blnDeleteErrmsgSent.value = $true
        }
      }
    }
  }
}

# Call Archive Function (auto-recursive) to archive any xml files in Folder, and subfolders
DelFiles $FolderPath ([ref]$blnDeleteErrmsgSent)

Exit

Yanıtlar

SimonS Sep 21 2020 at 18:51

Sanırım gerçekten çok uzakta değildin, ama işte benim farklı yapacağım üç şey:

  • Klasörden klasöre atlamak yerine , -Recurseanahtarını kullanarak tek bir komutla tüm dosyaları alın.Get-ChildItem
  • E-posta için bayraklar oluşturmak yerine, silme işleminiz sırasında göndermek istediğiniz bilgileri toplayın, bunları bir dizide saklayın ve ardından e-postayı bir kez gönderin
  • Silmek istediğiniz dosyanın bir klasör olmadığını kontrol etmek yerine, -Fileparametresini kullanın .Get-ChildItem

Bunu bir senaryo olarak da kullanırdım, a değil Function, ama bu senin çağrın:

$RootFolder = "C:\install\su1587308" $DeleteDate = (Get-Date).AddDays("-2")
$Fails = @() # Get all files below the rootfolder that are not ReadOnly: Get-ChildItem $RootFolder -Recurse -Attributes !ReadOnly -File |
  Where-Object { $_.LastWriteTime -lt $DeleteDate } | ForEach-Object {
    Try {
      Remove-Item $_.FullName -Force -ErrorAction Stop } Catch { # if it fails to the delete, the fullname of the file is stored in a variable $Fails += $_.FullName } } # Only send an email if something failed: if ($Fails) {
  $Body = "Could not delete the Following Files:<br>" +($Fails -join '<br>')
  $Splat = @{ SmtpServer = "???" From = "ScanDeletion@****.co.uk" To = "IT@****.co.uk" Subject = "errored while deleting old scan files" Body = $Body
    BodyAsHtml = $true
  }

  Send-MailMessage @Splat
}