【问题标题】:Catch Errors in interacive Powershell在交互式 Powershell 中捕获错误
【发布时间】:2017-03-08 20:28:32
【问题描述】:

如果尝试在 ineracvie powershell 中做某事,是否有可能捕获特定错误? 我的意思是:

powershell.exe
PS C:>_
PS C:>fuu
fuu: this is not a cmdlet .... BLA BLA BLA
+ ~~~
    + CategoryInfo          : ObjectNotFound: (fuu:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

这是 ineractive powershell 的正常行为。 我可以在我的 Profile.ps1 中放一些东西,以便一切都保持这样,但对于特定错误,例如这些 CommandNotFoundException,只有在这些错误上我才改变 powershell 的行为?也许是一个新的 wirte-host 或其他东西。

powershell.exe
PS C:>_
PS C:>fuu
fuu: this is not a cmdlet so CommandNotFoundException and now i behave diffrent my lord
PS C:>_

所以是的,我知道 try catch 等等 -> 在 SCRIPTS 但我的意思是交互作为默认行为!

谢谢

[更新]

把事情弄清楚。真正的案例是代码设计。 ExecutionPolicy 是 AllSignt,如果我忘记签署测试代码当然会出现错误:

+ ~~~~~~~~~~~~~~
    + CategoryInfo          : Sicherheitsfehler: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

但在这种情况下,我不想要这个错误,我想问一个问题,你想签名吗?是/否

....而不是那样做。

【问题讨论】:

    标签: powershell error-handling try-catch interactive


    【解决方案1】:

    使用这个结构:

    $Error.Clear()
    
    fooo
    
    $Errormessage = $Error | Out-String
    $Errormessage
    

    您将收到:

    fooo : The term 'fooo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
    path is correct and try again.
    At line:5 char:1
    + fooo
    + ~~~~
        + CategoryInfo          : ObjectNotFound: (fooo:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    

    当您有字符串时,您可以制作解析器并制作您的自定义错误处理程序,如

    $customerror = $Errormessage.reaplace("fooo : The term 'fooo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
    path is correct and try again.","Foo is not functin")
    
     write-output $customerror 
    

    【讨论】:

    • 但我如何将这些添加到正常的 PS 行为中?我不想在我的“fuu”调用中添加代码行。我想操纵 ineracive shell 的错误处理
    • @AnUser 你的意思是默认编辑powershell错误? .我不知道这是可能的。对不起,朋友 。我只是投票你的问题来成为最重要的问题。如果你愿意,我可以删除我的答案。
    • 谢谢,不,不要删除它,也许它会清除一些东西。
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2017-11-10
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多