Handle errors in ScriptBlock in Invoke-Command Cmdlet

后端 未结 4 1157
眼角桃花
眼角桃花 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 10:50

    No, you can't get the Errorvariable from the Invoke-Command call to be set the same as in the scriptblock.

    But if your goal is "detect and handle errors in the scriptblock, and also get errors returned back to the context of the Invoke-Command caller" then just do it manually:

    $results = Invoke-Command -ComputerName server.contoso.com -ScriptBlock {
       try
       {
           New-Service -ErrorAction 1
       }
       catch
       {
           
           return $_
       }
       
    }
    

    $results now contains the error information.

提交回复
热议问题