PowerShell错误处理调用命令

PowerShell错误处理调用命令,powershell,Powershell,出于这样或那样的原因,我似乎无法获取Invoke命令来生成错误并转到代码的Catch块。我可能遗漏了一些明显的东西,但我看不到 我知道在发现终止错误之前,Try块始终被执行。通过使用开关-ErrorAction Stop,我希望当服务器名称不存在时,它会成为终止错误,并转到Catch块报告此错误。但它实际上并没有这样做,它只是在不存在的服务器上使用Invoke命令启动作业。当不使用开关-AsJob时,会捕获错误。我有点困惑,在这里处理错误的最佳方法是什么 $Server = "Wrong" T

出于这样或那样的原因,我似乎无法获取
Invoke命令
来生成错误并转到代码的
Catch
块。我可能遗漏了一些明显的东西,但我看不到

我知道在发现终止错误之前,
Try
块始终被执行。通过使用开关
-ErrorAction Stop
,我希望当服务器名称不存在时,它会成为终止错误,并转到
Catch
块报告此错误。但它实际上并没有这样做,它只是在不存在的服务器上使用
Invoke命令启动作业。当不使用开关
-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变得越来越好,我希望能够帮助其他人。

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

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

这是我在电脑上为你做的一个测试场景 这是我在一台不存在的电脑上做的第一个

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上运行的脚本块捕获错误。AsJob将创建一个本地后台作业,以保持与远程服务器的连接。我想错误会被记录在那里,而不是本地会话中。谢谢harry sib,这正是我一直在寻找的。有点奇怪,
Invoke命令
在找不到客户端时不会生成错误,但这确实是由于
-AsJob
开关造成的。