2015-03-24 180 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 
}