在PowerShell 5.1中调用pwsh.exe如何仅获取脚本块返回值?
解决方法
问题根源
Write-Host的输出会发送到PowerShell的信息流(编号6),而非脚本返回值所在的成功输出流。默认调用pwsh.exe时,所有流的输出都会被捕获,导致结果混入无关内容。- 直接传递
ScriptBlock给pwsh.exe的执行逻辑存在解析歧义,容易产生重复输出,使用-Command参数明确执行方式更稳定。
具体解决方案
1. 移除或重定向无关输出
如果不需要Write-Host的内容,直接删除该语句;或者将其输出导向空,避免干扰结果:
$code = 'write-host 999 | Out-Null ; $a = @(1,2,3) ; return $a' $sb = [ScriptBlock]::Create($code) $result = pwsh.exe -NoProfile -Command $sb
执行后$result仅包含1,2,3。
2. 调用时过滤信息流
若需保留脚本内的Write-Host但不希望它出现在结果中,可在调用时将信息流重定向到$null:
$code = 'write-host 999 ; $a = @(1,2,3) ; return $a' $sb = [ScriptBlock]::Create($code) $result = pwsh.exe -NoProfile -Command "& {$sb} 6> $null"
此操作会丢弃Write-Host的输出,仅保留脚本返回的$a数组。
3. 明确输出目标变量
PowerShell中脚本最后一个表达式的结果会自动作为返回值,无需显式return,可以简化脚本逻辑:
$code = 'write-host 999 ; $a = @(1,2,3) ; $a' $sb = [ScriptBlock]::Create($code) $result = pwsh.exe -NoProfile -Command "& {$sb} 6> $null"
同样能得到仅包含1,2,3的结果。
验证结果
执行任意方案后,$result的输出为:
1 2 3
完全符合仅获取原$a的需求。
内容的提问来源于stack exchange,提问作者Birdy
相关产品推荐
相关产品推荐

