Powershell Script para exclusão recursiva

Sep 21 2020

Comecei um novo trabalho e quase instantaneamente fui chamado para fazer um Powershell, no entanto, eu só usei o Powershell no Exchange e muito básico nisso.

Estarei aprendendo mais nos próximos meses, mas, por enquanto, preciso de um script que vá para uma pasta arbitrária, verifique cada pasta e subpasta recursivamente, excluindo todos os arquivos com mais de 2 dias.

Alguém pode ajudar um novato nisso, 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

Respostas

SimonS Sep 21 2020 at 18:51

Acho que você não estava muito longe, mas aqui estão as três coisas que eu faria diferente:

  • Obtenha todos os arquivos com apenas um comando usando a -Recursechave de Get-ChildItem, em vez de pular de uma pasta para outra apenas para obter os arquivos dentro
  • Em vez de criar sinalizadores para o e-mail, reúna as informações que deseja enviar durante o processo de exclusão, armazene-as em uma matriz e envie o e-mail uma vez
  • Em vez de verificar se o arquivo que você deseja excluir não é uma pasta, use o -Fileparâmetro deGet-ChildItem

Eu também o usaria como um script, não um Function, mas você decide:

$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
}