Powershell - Run external powershell script and capture output - Can't pass parameters

user3894477 picture user3894477 · Sep 15, 2014 · Viewed 10.9k times · Source

I have a problem running a powershell script from within another powershell script, passing parameters and capturing the output.
I have tried using the ampersand operator, calling it via powershell.exe -Command but nothing seems to work.
What really drives me mad is, that I can execute the script without parameters and capture the output, but as soon as parameters join the game everything goes crazy.
It seems that many people know this problem, but unfortunately I couldn't find a solution.

What seems to work is using fixed parameter and values stored in a variable like this C:\path\to\script.ps1 -arg1 $value.
This may present a solution if nothing else works, but I would like to run the command similar to this & $pathToScript $params 2>&1 (the 2>&1is for capturing error output as well as standard).

Any help is highly appreciated and if you're able to point me in the right direction I will name the function after you!
Thanks in advance.

Edit:
Forgot to include Error messages, I'm sorry.
Sometimes the construct prints just the path to the script,
sometimes it says Cannot run file in the middle of pipeline and
sometimes it complains about it cannot find the mentioned script file (I sometimes have spaces in my path, but I thought quoting it would suffice: quoting was done like this $path = "`"C:\path\with space\to\script.ps1`"").

This is the simplified function I want to use this in:

Function captureScriptOutput
{
    #the function receives the script path and parameters
    param($path, $params)

    #this works if no params are passed, but I need params!
    $output = & $path $params 2>&1 | Out-String
}

Answer

user3894477 picture user3894477 · Sep 16, 2014

I solved the problem with the help of a colleague.

We went a little indirection and included a cd into the respective directory and ran the command afterwards. This works like a charm.

Solution source code:

Function captureScriptOutput
{
    param($fileName, $params)

    cd "C:\into\path with\space"
    $output = & .\$fileName $params 2>&1 | Out-String
}

This works and even captures the error output, I hope some other folks encountering this kind of problem can use this to fix their problems.

Cheerioh and thanks for reply!