Script de Powershell para eliminación recursiva

Sep 21 2020

Comencé un nuevo trabajo y casi instantáneamente fui enviado para hacer algo de Powershell, sin embargo, solo he usado Powershell en Exchange y es muy básico en eso.

Aprenderé más durante los próximos meses, pero por ahora, necesito un script que vaya a una carpeta arbitraria, verifique cada carpeta y subcarpeta de forma recursiva, eliminando cualquier archivo de más de 2 días.

¿Alguien puede ayudar a un novato en esto, por favor?

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

Respuestas

SimonS Sep 21 2020 at 18:51

Creo que no estabas muy lejos, pero estas son las tres cosas que haría de manera diferente:

  • Obtenga todos los archivos con un solo comando usando el -Recurseinterruptor de Get-ChildItem, en lugar de saltar de carpeta en carpeta solo para obtener los archivos dentro
  • En lugar de crear indicadores para el correo electrónico, recopile la información que desea enviar durante el proceso de eliminación, guárdelos en una matriz y luego envíe el correo electrónico una vez.
  • En lugar de verificar si el archivo que desea eliminar no es una carpeta, use el -Fileparámetro deGet-ChildItem

También lo usaría como un script, no como un Function, pero esa es tu decisió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
}