Powershell Script per l'eliminazione ricorsiva
Sep 21 2020
Ho iniziato un nuovo lavoro e quasi immediatamente sono stato lasciato cadere per fare un po 'di Powershell, tuttavia ho sempre usato Powershell in Exchange e in modo molto semplice.
Imparerò di più nei prossimi mesi, ma per ora ho bisogno di uno script che vada in una cartella arbitraria, controlli ogni cartella e sottocartella in modo ricorsivo, eliminando tutti i file più vecchi di 2 giorni.
Qualcuno può aiutare un principiante su questo, per favore? '
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
Risposte
SimonS Sep 21 2020 at 18:51
Penso che non fossi molto lontano, ma ecco le tre cose che avrei fatto in modo diverso:
- Ottieni tutti i file con un solo comando utilizzando l'
-Recurseopzione diGet-ChildItem, invece di saltare da una cartella all'altra solo per ottenere i file all'interno - Invece di creare flag per l'e-mail, raccogli le informazioni che desideri inviare durante il processo di eliminazione, memorizzale in un array, quindi invia l'e-mail una volta
- Invece di controllare se il file che desideri eliminare non è una cartella, utilizza il
-FileparametroGet-ChildItem
Lo userei anche come script, non come Function, ma questa è la tua chiamata:
$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
}