2015-03-24 186 views
0

我有一個PowerShell腳本,它查找文件夾中的文件並將其移動到另一個文件夾,並使用日期擴展名重命名文件。 像這樣:Powershell的電子郵件錯誤

$a = "\\server\Users\Desktop\why agile.docx" 
$f = "\\server\Users\desktop\Archive\why agile.docx" 

Move-item $a $f 

Function renameFile ($location, $filename, $extension) 
{ 
    $d = get-date -uformat "%Y%m%d" 

    $old = $location + $filename + $extension 
    $new = $filename + "_" + $d + $extension 
    rename-item $old $new 
} 

renamefile -location "\\server\Users\desktop\Archive\" -filename "why agile" -extension ".docx" 

我的問題是:我如何可以添加到這個腳本以電子郵件的任何錯誤信息,或者如果有丟失的文件,重複的文件,或者如果過程由於某種原因失敗(超時,等等...)?

感謝,

+0

[這](https://social.technet.microsoft.com/Forums/windowsserver/en-US/5f7a9d63-6a37-4d98-b710-d76fde920a37/how-to-get-powershell-script-發送電子郵件附帶文件)可能會有所幫助! – ConfusedMan 2015-03-24 22:32:07

回答

1

要擴展其他答案,您可以將代碼包裝在try塊中,然後在catch塊中,通過電子郵件發送錯誤。

喜歡的東西

try { 
    rename file ... 
} 
catch [Exception] { 
    Send-MailMessage ... 
} 
+0

try {} catch {}完美地工作。在'try {move-item $ a $ f -ErrorAction stop'}上捕獲{$ ErrorMessage = $ _。Exception.Message $ FailedItem = $ _。Exception.ItemName Send-MailMessage - From [email protected] .com -To [email protected] -Subject「」-SmtpServer'' - Body $ ErrorMessage「 – BIReportGuy 2015-03-25 16:01:36

+1

我的聲望還不足以評論你的答案,所以我會在這裏評論你的嘗試/ catch語句應該真正在你的函數中,而不是將你的整個腳本包裝在它們中。如果你想測試移動和重命名,並且在函數中有一個,而在函數中有一個,我會爲每個都有一個try/catch。然後編寫一個函數來發送一個叫做電子郵件的函數,也可以傳遞一個消息,說明它在移動或重命名時失敗了,你也要遵循清除錯誤的建議。 – 2015-03-25 18:29:09

2

清除$Error自動變量,並設置$ErrorActionPreferenceSilentlyContinue,然後再開始。 Send an e-mail$Error變量的內容,如果它不是空的,你完成之後:

$Error.Clear() 
$eap = $ErrorActionPreference 
$ErrorActionPreference = 'SilentlyContinue' 

renamefile ... 

if ($Error) { 
    Send-MailMessage -From $sender -To $recipient -Body ($Error -join "`n") ... 
} 

$ErrorActionPreference = $eap 

連續服用缺少照顧或重複的文件添加相應的檢查。

0

這裏就是我終於實現了。我使用了try { } catch { },它效果很好。感謝大家的幫助......讓我指出了正確的方向。我是Powershell的新手。

try 
{ 
$a = "\\servername\Users\Desktop\agile.docx" 
$b = "\\servername\Users\Desktop\Archive\agile.docx" 


Move-item $a $b -ErrorAction stop 

Function renameFile ($location, $filename, $extension) 
{ 
    $d = get-date -uformat "%Y%m%d" 

    $old = $location + $filename + $extension 
    $new = $filename + "_" + $d + $extension 
    rename-item $old $new 
} 

renamefile -location "\\servername\Users\desktop\Archive\" -filename "Agile" -extension ".docx" 

} 
Catch 
{ 
    $ErrorMessage = $_.Exception.Message 
    $FailedItem = $_.Exception.ItemName 
    Send-MailMessage -From [email protected] -To [email protected] -Subject "Files Failed to Transfer to Archive Folder!" -SmtpServer smtp... -Body "The error message is: '$ErrorMessage'" 
    Break 
}