我在處理有關invoke-command的錯誤/異常時遇到了一些問題。Powershell錯誤/異常處理
我試圖捕捉目標計算機不存在的錯誤,但是我顯示的消息和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爲空的不同錯誤。
當我做了一個-contains
使用顯示的錯誤信息中關於$ session的單詞,它仍然返回false我測試的每個單詞。
我不明白其中哪些是錯誤,爲什麼不是-contains
永遠返回true。我將-ea stop
添加到所有3行以捕獲所有非終止錯誤,但無濟於事。
任何人有任何想法是怎麼回事?
thnx。抱歉遲到接受,但這確實解決了我的問題。 – user1752736