Handle errors in ScriptBlock in Invoke-Command Cmdlet

后端 未结 4 1160
眼角桃花
眼角桃花 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条回答
  •  -上瘾入骨i
    2020-12-06 10:56

    The Invoke-Command argument list is a one way deal. You can either output the error variable in the script e.g. on the last line of the scriptblock put:

    $errortext
    

    or better yet, just don't capture the error via the -ErrorVariable at all. The scriptblock output, including errors, will flow back to the caller even over a remote connection.

    C:\> Invoke-Command -cn localhost { Get-Process xyzzy } -ErrorVariable errmsg 2>$null
    C:\> $errmsg
    Cannot find a process with the name "xyzzy". Verify the process name and call the cmdlet again.
        + CategoryInfo          : ObjectNotFound: (xyzzy:String) [Get-Process], ProcessCommandException
        + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand
        + PSComputerName        : localhost
    

    In general, I think it is much better to keep errors on the error stream, separated from the normal output.

提交回复
热议问题