Handle errors in ScriptBlock in Invoke-Command Cmdlet

后端 未结 4 1170
眼角桃花
眼角桃花 2020-12-06 10:35

I am trying to install a service on a remote machine using the powershell.

So far I have the following:

Invoke-Command -ComputerName  $remoteComputer         


        
4条回答
  •  生来不讨喜
    2020-12-06 11:08

    This is almost certainly not the "correct" answer, but this is what I use when I want Invoke-Command to throw an error in the script.

    $error.Clear()
    Invoke-Command -ComputerName localhost -ScriptBlock {Command-ThatFails}
    $if ($error.Count -gt 0) { throw $error[0] }
    

    If you wanted to keep the error in a variable, you could do the following:

    $error.Clear()
    Invoke-Command -ComputerName localhost -ScriptBlock {Command-ThatFails}
    $if ($error.Count -gt 0) { $myErrorVariable = $error[0] }
    

提交回复
热议问题