PowerShell错误处理Invoke-Command

时间:2014-06-15 14:07:53

标签: powershell

由于某种原因,我似乎无法让Invoke-Command产生错误并转到代码的Catch块。我可能在这里遗漏了一些明显的东西,但我看不到它。

我知道Try块始终执行,直到找到Terminating错误。通过使用开关-ErrorAction Stop,我希望它在服务器名称不存在时成为终止错误,并转到Catch块以报告此错误。但它并没有真正做到这一点,它只是在不存在的服务器上使用Invoke-Command启动作业。当不使用开关-AsJob时,会捕获错误。我对这里错误处理的最佳方法感到困惑。

$Server = "Wrong"

Try {
         if ($Server -eq "UNC") {
             Write-Host "Running Start-Job" -ForegroundColor Cyan
             Start-Job -ScriptBlock { Write-Host "Foo Start-Job" } -Name DelFiles
         }
         else {
              Write-Host "Running Invoke-Command" -ForegroundColor Cyan        
              Invoke-Command -ScriptBlock { Write-Host "Foo Invoke-Command" } -ComputerName "$Server" -AsJob -JobName DelFiles -ErrorAction Stop
         }  
     }
Catch {
    Write-Host "Error detected"
}

感谢您的帮助,我在StackOverflow上学到了很多东西。一旦我在PowerShell上变得更好,我希望能够帮助其他人。

1 个答案:

答案 0 :(得分:3)

正如@mjolinor所说。该错误将在作业中捕获,因此您需要get-jobreceive-job来查看是否存在错误。

get-job [id]会为您显示该作业,您可以查看state以查看它是否失败或已完成或仍在运行,receive-job [id]将回显任何可能的内容通常打印到stdout

这是我在电脑上做的一些测试场景 这是我在不存在的PC上做的第一个

PS C:\hht> Invoke-Command -ScriptBlock { echo "hey"} -ComputerName test-pc -AsJob
Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
22     Job22           RemoteJob       Running       True            test-pc               echo "hey"              

PS C:\hht> Get-Job 22

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
22     Job22           RemoteJob       Failed        False           test-pc               echo "hey"

PS C:\hht> Receive-Job 22

[test-pc] Connecting to remote server test-pc failed with the following error message : WinRM cannot process the request. The following error occurred while using 
Kerberos authentication: Cannot find the computer test-pc. 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: (test-pc:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken

正如您所看到的那样失败,因此您可以在主脚本中捕获此内容,例如:

if((get-job $id).state -eq "Failed")
{
    echo "There was an error running job on $server"
}

这是一个有效的例子:

PS C:\hht> Invoke-Command -ScriptBlock { echo "hey"} -ComputerName test2-pc -AsJob
Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
24     Job22           RemoteJob       Running       True            test-pc               echo "hey"  

PS C:\hht> Get-Job 24

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
24     Job24           RemoteJob       Completed     False           test2-pc       echo "hey" 

PS C:\hht> Receive-Job 24
hey

正如您所见,此作业已成功完成,并且正在运行receive-job将返回在远程PC上运行的作业的输出

因此,在您的代码中,try-catch块只会捕获本地会话上的任何错误,而不会捕获远程PC上运行的脚本块