2016-09-27 54 views
1

此腳本的預期結果是找出主機列表上的PowerShell版本。我想在遠程機器關閉或未啓用遠程處理時處理異常。但是,似乎沒有輸入catch。出現PowerShell的標準紅色火焰錯誤消息。處理遠程連接異常

我需要做什麼來捕捉異常?

X:\Scripts\PSAutomation> Get-Content .\get-versions.ps1 
server_list = @(
    'CAPPY' 
) 

$server_list | 
    ForEach-Object { 
     Try { 
      Invoke-Command -ComputerName $_ {$PSVersionTable.PSVersion} 
     } 
     Catch 
     { 
      Write-Host "Failed to connect to $_" 
     } 
    } 
X:\Scripts\PSAutomation> .\get-versions.ps1 
[CAPPY] Connecting to remote server CAPPY failed with the following error message : WinRM cannot process the 
request. The following error occurred while using Kerberos authentication: Cannot find the computer CAPPY. Verify 
that the computer exists on the network and that the name provided is spelled correctly. For more information, see 
the about_Remote_Troubleshooting Help topic. 
    + CategoryInfo   : OpenError: (CAPPY:String) [], PSRemotingTransportException 
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken 

回答

1

只需設置ErrorAction爲呼叫stop

Invoke-Command -ComputerName "sdf" {$PSVersionTable.PSVersion} -ErrorAction Stop 
+0

使用'-ErrorAction'使紅色消息出現在正常控制檯文本顏色。但是,沒有任何關於'Write-Host'的信息出現。 – lit

+0

我認爲你錯了,消息應該以連接失敗開始......那是因爲你的catch塊中的$ _代表錯誤而不是當前的foreach對象管道變量。您可能必須在嘗試之前引入一個變量,例如:'$ current = $ _'並在您的寫主機中使用'$ current'而不是'$ _' –

+0

是的。你是對的。我應該看到它。 – lit