Powershell Script để xóa đệ quy
Sep 21 2020
Tôi đã bắt đầu một công việc mới và gần như ngay lập tức được mời làm một số Powershell, tuy nhiên tôi chỉ mới sử dụng Powershell trong Exchange và rất cơ bản về điều đó.
Tôi sẽ học thêm trong vài tháng tới nhưng hiện tại, tôi cần một tập lệnh sẽ chuyển đến một thư mục tùy ý, kiểm tra mọi thư mục và thư mục con một cách đệ quy, xóa bất kỳ tệp nào cũ hơn 2 ngày.
Bất cứ ai có thể giúp một người mới về việc này, xin vui lòng? '
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
Trả lời
SimonS Sep 21 2020 at 18:51
Tôi nghĩ rằng bạn đã không thực sự đi xa, nhưng đây là ba điều tôi sẽ làm khác:
- Nhận tất cả các tệp chỉ bằng một lệnh bằng cách sử dụng công
-RecursetắcGet-ChildItemthay vì chuyển từ thư mục này sang thư mục khác chỉ để lấy các tệp bên trong - Thay vì tạo cờ cho email, hãy thu thập thông tin bạn muốn gửi trong quá trình xóa, lưu trữ chúng trong một mảng, sau đó gửi email một lần
- Thay vì kiểm tra xem tệp bạn muốn xóa có phải là một thư mục hay không, hãy sử dụng
-Filetham sốGet-ChildItem
Tôi cũng sẽ sử dụng nó như một tập lệnh, không phải a Function, nhưng đó là cách gọi của bạ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
}