【问题标题】:Powershell error/exception handlingPowershell 错误/异常处理
【发布时间】:2013-05-30 19:23:32
【问题描述】:

我在处理有关调用命令的错误/异常时遇到了一些问题。

当目标计算机不存在时,我试图捕获错误,但是显示的消息和 catch 块中的脚本的行为方式让我觉得我错过了或错过了理解。

这是有问题的脚本部分:

$session = New-Pssession -computername $computerName 
Invoke-Command -session $session -ScriptBlock $command -ArgumentList $sqlServerName, $userToGivePermisions          
Remove-PSsession -session $session

基本上,当$computerName 不是网络上的有效计算机时,我想处理错误。我故意给它一个错误的名字来测试它,我得到以下错误:

[dcd] Connecting to remote server failed with the following error message : WinRM cannot process the request. The following error occured while using Kerberos authentication: The network path was not found.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between     the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM  TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace)   [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed

[dcd] 是不存在机器的名称。我将代码放入 try catch 并使用 -contains 检查错误消息。条件总是错误的,我在上面的错误中几乎尝试了一个单词。

当我使用$_.exception.message 在 catch 块中显示错误消息时,我得到了一个关于 $session 为空的不同错误。

当我使用显示的有关 $session 的错误消息中的单词执行-contains 时,它仍然为我测试的每个单词返回 false。

我不明白其中哪一个是错误,为什么 -contains 不返回 true。我将-ea stop 添加到所有 3 行以捕获所有非终止错误但无济于事。

有人知道发生了什么吗?

【问题讨论】:

    标签: powershell error-handling try-catch invoke-command


    【解决方案1】:

    -contains 检查元素是否在数组中。例如:

    1,2,3 -contains 2 # Is True
    "a","bc","d" -contains "b" # Is False
    

    改用-match-like 运算符。看看comparison operator documentation

    【讨论】:

    • 谢谢。很抱歉迟到了,但这确实解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-02-28
    • 2012-09-15
    • 2011-04-03
    • 2014-01-08
    • 2014-04-06
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多