简体   繁体   English

Powershell:无法将Invoke-Expression的输出存储在变量中

[英]Powershell: Can't store the output from Invoke-Expression in a variable

I've got a fairly lengthy Powershell script that I'd like to call from another script. 我有一个很长的Powershell脚本,我想从另一个脚本中调用。 Currently, I'm using Invoke-Expression to make this call, and it works well: 目前,我正在使用Invoke-Expression进行此调用,并且效果很好:

    $argumentList = @()
    $argumentList += ("-oldaccount", ($oldDomain + "\" + $oldUname), "-newaccount", ($newDomain + "\" + $newUname))

    $output = Invoke-Expression "C:\path\to\script.ps1 $argumentList"

The script that I'm calling writes its output lines to the screen using Write-Host. 我正在调用的脚本使用Write-Host将其输出行写入屏幕。 I'd like to capture this output in the caller script so that I can put it in a log file, and ideally I'd like to do this without modifying the script that I'm calling. 我想在调用者脚本中捕获此输出,以便可以将其放在日志文件中,并且理想情况下,我希望在不修改正在调用的脚本的情况下执行此操作。 I've tried the suggestion in How to pipe output of Invoke-Expression to string? 我已经尝试了如何将Invoke-Expression的输出传递给字符串的建议? with no luck - when I run the code in ISE, I just get the output to the screen and the variable stays empty. 运气不好-当我在ISE中运行代码时,我只是将输出输出到屏幕,并且变量保持为空。 Do I need to do something different since I'm calling another Powershell script and not an executable? 因为我要调用另一个Powershell脚本而不是可执行文件,我是否需要做其他事情?

Write-Host will not work for you. 写主机将不适用于您。 Try returning a value in your inner script for example: 尝试在内部脚本中返回一个值,例如:

InnerScript.ps1 could be: InnerScript.ps1可以是:

return "Test"

And then OuterScript.ps1 should be: 然后OuterScript.ps1应该是:

$output = Invoke-Expression ".\InnerScript.ps1"

Write-Host($output) should show: Write-Host($ output)应该显示:

Test

Adapt this example to your specific scenario. 将此示例调整为适合您的特定方案。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM