Powershell Script untuk penghapusan rekursif
Saya telah memulai pekerjaan baru dan hampir seketika ditempatkan untuk melakukan Powershell, namun saya hanya pernah menggunakan Powershell di Exchange dan sangat mendasar dalam hal itu.
Saya akan melakukan lebih banyak pembelajaran selama beberapa bulan ke depan tetapi untuk saat ini, saya memerlukan skrip yang akan masuk ke folder sewenang-wenang, memeriksa setiap folder dan subfolder secara rekursif, menghapus file apa pun yang berusia lebih dari 2 hari.
Adakah yang bisa membantu seorang pemula dalam hal ini? '
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
Jawaban
Saya pikir Anda tidak terlalu jauh, tetapi berikut adalah tiga hal yang akan saya lakukan berbeda:
- Dapatkan semua file hanya dengan satu perintah dengan menggunakan
-Recursesakelar dariGet-ChildItem, alih-alih melompat dari folder ke folder hanya untuk memasukkan file di dalamnya - Alih-alih membuat bendera untuk email, kumpulkan informasi yang ingin Anda kirim selama proses penghapusan, simpan dalam larik, lalu kirim email sekali
- Alih-alih memeriksa apakah file yang ingin Anda hapus bukan folder, gunakan
-FileparameterGet-ChildItem
Saya juga akan menggunakannya sebagai skrip, bukan a Function, tapi itulah panggilan Anda:
$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
}