สคริปต์ Powershell สำหรับการลบแบบวนซ้ำ
Sep 21 2020
ฉันได้เริ่มงานใหม่และเกือบจะถูกทิ้งให้ทำ Powershell ในทันทีอย่างไรก็ตามฉันเคยใช้ Powershell ใน Exchange เท่านั้นและเป็นพื้นฐานมากในเรื่องนั้น
ฉันจะทำการเรียนรู้เพิ่มเติมในอีกไม่กี่เดือนข้างหน้า แต่ตอนนี้ฉันต้องการสคริปต์ที่จะไปยังโฟลเดอร์โดยพลการตรวจสอบทุกโฟลเดอร์และโฟลเดอร์ย่อยแบบวนซ้ำโดยลบไฟล์ใด ๆ ที่มีอายุเกิน 2 วัน
ใครช่วยมือใหม่เรื่องนี้หน่อยได้ไหม? '
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
คำตอบ
SimonS Sep 21 2020 at 18:51
ฉันคิดว่าคุณไม่ได้อยู่ไกล แต่นี่คือสามสิ่งที่ฉันจะทำแตกต่างกัน:
- รับไฟล์ทั้งหมดด้วยคำสั่งเพียงคำสั่งเดียวโดยใช้
-Recurseสวิตช์Get-ChildItemแทนที่จะกระโดดจากโฟลเดอร์หนึ่งไปอีกโฟลเดอร์เพื่อรับไฟล์ภายใน - แทนที่จะสร้างแฟล็กสำหรับอีเมลรวบรวมข้อมูลที่คุณต้องการส่งในระหว่างขั้นตอนการลบเก็บไว้ในอาร์เรย์จากนั้นส่งอีเมลครั้งเดียว
- แทนที่จะตรวจสอบว่าไฟล์ที่คุณต้องการลบไม่ใช่โฟลเดอร์หรือไม่ให้ใช้
-Fileพารามิเตอร์ของGet-ChildItem
ฉันจะใช้มันเป็นสคริปต์ไม่ใช่ a Functionแต่นั่นคือคำเรียกของคุณ:
$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
}