powershell - 从远程系统上的 Invoke-Command 捕获 Write-Host 输出和退出代码

标签 powershell powershell-4.0 powershell-remoting exit-code write-host

我有一个位于远程系统上的脚本。

在 C:\tmp\hgttg.ps1 下的服务器“web12”上:

 Write-Host "Don't Panic"
 exit 42

我使用 Invoke-Command 从我的本地机器(两个运行 v4.0 的系统)调用这个脚本:

$svr = "web12"
$cmd = "C:\tmp\hgttg.ps1"
$result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd}

这会在执行时产生以下输出:

> $result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd}
Don't Panic
> $result
>

(未设置 $result,输出直接到控制台,不好!)经过大量网络搜索和故障排除,我有了一些改进:

> $result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd; $LASTEXITCODE}
Don't Panic
> $result
42
>

现在我能够捕获返回代码,但输出仍然直接进入控制台。这是我能得到的。在我已经尝试过的一长串事情中,以下都没有奏效:

  • 使用带有 -OutVariable out 的 'Invoke-Expression' 而不是 '&';新对象 -TypeName PSCustomObject -Property @{code=$LASTEXITCODE;输出=$out}

这会产生输出:

> $result
code           : 42
output         : 
PSComputerName : web12
RunspaceId     : aaa00a00-d1fa-4dd6-123b-aa00a00000000
> 
  • 尝试在内部和外部命令末尾使用“4>&1”和“*>&1”进行上述两次迭代,没有任何变化。

  • 尝试了每一个:

    1. "& $using:cmd | Tee-Object -变量输出;$out"
    2. "& $using:cmd >$out; $out"
    3. “$out = & $using:cmd; $out”

    (丢弃返回代码只是为了获得输出)同样,没有变化。

  • 还尝试:'& $using:cmd >> C:\tmp\output.log; $LASTEXITCODE'。生成的文件是空的,文本仍然输出到本地终端。

我敢肯定我遗漏了一些明显的东西,但到目前为止我遇到的都是死胡同。有什么建议吗?

最佳答案

PSv4-(4.x 或更低版本)上,无法捕获Write-Host 输出 - 它总是直接进入控制台。

PSv5+ 中,Write-Host(也)写入新引入的信息流,新引入的Write-Information cmdlet 旨在写入; 它的编号是6

因此,如果您的目标主机运行 PSv5+,您可以使用以下命令;请注意 *> 如何通过将它们重定向 (&) 到成功流 (1) 来捕获 所有 输出流,但您可以使用 6> 有选择地捕获信息流):

$result = Invoke-Command -ComputerName $svr -ScriptBlock {& $using:cmd *>&1; $LASTEXITCODE}
$output = $result[0..($result.Count-2)]
$exitCode = $result[-1]

关于powershell - 从远程系统上的 Invoke-Command 捕获 Write-Host 输出和退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524103/

相关文章:

powershell - 来自导入模块的函数在 powershell 脚本中不可用

Powershell Get-EventLog 一次返回一个事件

events - Powershell事件转发

在 PS v4 上运行时,Powershell v2.0 Foreach 循环失败

powershell - 如何获取站点的物理路径属性

powershell - 依靠PowerShell中的空列表

powershell - Invoke-WebRequest是否可以使用运行脚本的用户的用户凭据透明地进行身份验证?

powershell - 拥有 MFA 时使用 Windows Powershell ISE for Exchange

powershell - 如何使用Powershell移动和重命名多个文件?

Powershell 脚本无法识别 DevOps Pipeline 中的文件