PowerShell尝试,捕获,自定义终止错误消息 [英] PowerShell Try, Catch, custom terminating error message

查看:80
本文介绍了PowerShell尝试,捕获,自定义终止错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以自定义终止错误的错误消息?

Is there a way to customize the error message of a terminating error?

在下面的示例中,我只想结束一个 Try 部分,并将所有错误收集到一个捕获部分,将两个脚本块组合在一起。我的问题是由 Import-csv 生成的 $ error 的描述性不够,我想输入文字在 $ error 消息中, CSV文件导入c:\test.csv 失败。

In the example below I would like to just end up with one Try section and collect all errors in one Catch section by combining both script blocks. My problem is that the $error generated by Import-csv is not descriptive enough and I would like to have the text Failed CSV-File import c:\test.csv within the $error message.

谢谢您的建议。

脚本块1

Try {
    $File = (Import-Csv -Path c:\test.csv)
}
Catch {
    throw $error[0].Exception.Message | Send-Mail $ScriptAdmin "FAILED CSV-File import"
}

脚本区块2

try {
    if(!(Test-Path $LogFolder -PathType Container)) {throw "Can't find the log folder: '$LogFolder'"}
    $Credentials = Import-Credentials $UserName $PasswordFile
}
catch {
    throw $Error[0].Exception.Message | Send-Mail $ScriptAdmin "FAILURE"
}

解决方法

可能的解决方案是先使用 test-path 检查导入文件是否存在,然后创建投掷(带有自定义消息)。但是我想知道是否可以在一行代码中处理它而无需先使用 test-path

A possible solution would be to check first with test-path if the import file exists and then create a throw with a customized message. But I would like to know if it's possible to handle it in one line of code without using test-path first.

最佳解决方案(感谢mjolinor):

try {
    $File = (Import-Csv -Path $ImportFile -Header "A", "B", "C", "D" | Where { $_.A -NotLike "#*" })
    if(!(Test-Path $LogFolder -PathType Container)) {throw "Can't find the log folder: '$LogFolder'"}
    $Credentials = Import-Credentials $UserName $PasswordFile
}
catch {
    Switch -Wildcard ($Error[0].Exception)
        {
           "*$ImportFile*"
           { $FailType = "FAILED CSV-File import" }

           "*$LogFolder*"
           { $FailType = "FAILED Log folder not found" }

           "*Import-Credentials*"
           { $FailType = "FAILED Credential import" }

           Default
           { $FailType = "FAILED Unrecognized error" }

         }
       Write-Warning $Error[0].Exception.Message
       throw $Error[0].Exception.Message | Send-Mail $ScriptAdmin $FailType
}




  • 确保您创建的高级功能(如上面的导入凭据)在 throw 部分中包含函数名称。因此,我们可以在 catch 块中将其过滤掉。

    • Make sure that your advanced-function which you created (like Import-Credentials above) contains the function name in the throw section. So we can filter it out in the catchblock.
    • 推荐答案

      也许是这样的

      Try {
            $File = (Import-Csv -Path c:\test.csv)
      
            if(!(Test-Path $LogFolder -PathType Container)) 
            { throw "Can't find the log folder: '$LogFolder'" }
      
            $Credentials = Import-Credentials $UserName $PasswordFile
      
            }
      
      catch {
              Switch -Wildcard ($Error[0].CategoryInfo)
              {
                 '*[Import-CSV]*' 
                 { $FailType = 'Import CSV failed' }
      
                 '*[Test-Path]*'
                 { $FailType = 'LogFolder not found' }
      
                 '*[Import-Credentials]*'
                 { $FailType = 'Credential import failed' }
      
                 Default
                 { $FailType = 'Unrecognized error' }
      
               }
      
               $Error[0].Exception.Message | Send-Mail $ScriptAdmin $FailType
      
             }
      

      编辑(由于某些原因)我无法发表评论):

      Edit (for some reason I'm not able to post a comment):

      我应该指定它未经测试,并且更多地是作为一种模式而不是最终的解决方案,并且

      I should have specified that it wasn't tested, and was intended more as a pattern than a finished solution, and it seems to have done what it was intended to do.

      @BartekB-我习惯性地使用$ Error [0]而不是$ _,因为它看起来更加明确和直观阅读,并且不太可能被经验不足的人误解,他们以后可能会继承代码。

      @BartekB - I habitually use $Error[0] instead of $_ because it seems more explicit and intuitive to read, and less likely to be misunderstood by someone less experienced who might inherit the code later.

      这篇关于PowerShell尝试,捕获,自定义终止错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆