简体   繁体   中英

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. Currently, I'm using Invoke-Expression to make this call, and it works well:

    $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. 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? with no luck - when I run the code in ISE, I just get the output to the screen and the variable stays empty. Do I need to do something different since I'm calling another Powershell script and not an executable?

Write-Host will not work for you. Try returning a value in your inner script for example:

InnerScript.ps1 could be:

return "Test"

And then OuterScript.ps1 should be:

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

Write-Host($output) should show:

Test

Adapt this example to your specific scenario. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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