我有一个位于远程系统上的脚本。
在服务器“web12”上的 C:\tmp\hgttg.ps1 下:
Write-Host "Don't Panic"
exit 42
Run Code Online (Sandbox Code Playgroud)
我使用 Invoke-Command 从本地机器(两个系统都运行 v4.0)调用此脚本:
$svr = "web12"
$cmd = "C:\tmp\hgttg.ps1"
$result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd}
Run Code Online (Sandbox Code Playgroud)
执行时会产生以下输出:
> $result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd}
Don't Panic
> $result
>
Run Code Online (Sandbox Code Playgroud)
($result未设置,输出直接到控制台,不好!)经过大量的网络搜索和故障排除,我得到了一些改进:
> $result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd; $LASTEXITCODE}
Don't Panic
> $result
42
>
Run Code Online (Sandbox Code Playgroud)
现在我可以捕获返回代码,但输出仍然直接发送到控制台。这是我所能得到的。在我已经尝试过的一长串事情中,以下任何一项都不起作用:
这会产生输出:
> $result
code : 42
output :
PSComputerName : web12 …Run Code Online (Sandbox Code Playgroud) powershell exit-code powershell-remoting powershell-4.0 write-host