【问题标题】:Email Errors with PowershellPowershell 的电子邮件错误
【发布时间】:2015-03-24 22:12:33
【问题描述】:

我有一个 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"

我的问题是:如何添加到此脚本以通过电子邮件发送任何错误消息,或者是否存在丢失文件、重复文件或进程由于某种原因(超时等)失败?

谢谢,

【问题讨论】:

  • This 可能会有所帮助!

标签: powershell powershell-2.0 powershell-3.0 powershell-ise


【解决方案1】:

在开始之前清除$Error 自动变量并将$ErrorActionPreference 设置为SilentlyContinueSend 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

为了处理丢失或重复的文件,请添加适当的检查。

【讨论】:

    【解决方案2】:

    要扩展其他答案,您可以将代码包装在 try 块中,然后在 catch 块中,通过电子邮件发送错误。

    有点像

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

    【讨论】:

    • try { } catch {} 完美运行。在 'try {move-item $a $f -ErrorAction stop} On the Catch { $ErrorMessage = $_.Exception.Message $FailedItem = $_.Exception.ItemName Send-MailMessage -From my.name@mycompany.com -To my.name@mycompany.com -Subject " " -SmtpServer ' ' - Body $ErrorMessage"
    • 我的声誉不够高,无法评论您的答案示例,因此我将在此处发表评论。你的 try/catch 语句应该真的在你的函数里面,而不是把你的整个脚本包装在里面。如果您想测试移动和重命名,并且在函数中有一个,一个不在函数中,我会为每个函数设置一个 try/catch。然后编写一个函数来发送被调用的电子邮件。您还可以传递一条消息,说明它在移动或重命名时失败。您还需要先遵循清除错误的建议。
    【解决方案3】:

    这就是我最终要做的。我使用了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 my.name@mycompany.com -To her.name@mycompany.com -Subject "Files Failed to Transfer to Archive Folder!" -SmtpServer smtp... -Body "The error message is: '$ErrorMessage'"
        Break
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2015-12-24
      相关资源
      最近更新 更多