Powershell - running external powershell script and outputting output - unable to pass parameters

I'm having a problem running a powershell script from another powershell script, passing parameters and capturing the output.
I tried using the ampersand operator, calling it through powershell.exe -Command

, but nothing seems to work.
It really pisses me off that I can execute a script without parameters and grab the output, but as soon as the parameters are attached to the game, things get crazy.
It seems like a lot of people are aware of this problem, but unfortunately I couldn't find a solution.

Seems to work using a fixed parameter and values ​​stored in a variable like this C:\path\to\script.ps1 -arg1 $value

.
This might lead to a solution if nothing else works, but I would like to run a command similar to this one & $pathToScript $params 2>&1

( 2>&1

- to output the error output as well as the standard one).

Any help is much appreciated and if you can point me in the right direction I will name it after you! Thanks in advance.

Edit:
Forgot to enable error messages, sorry.
Sometimes the construct only prints the path to the script,
sometimes it says Cannot run file in the middle of pipeline

and sometimes it complains about not being able to find the script file mentioned (I sometimes have spaces in my path, but I thought quoting would be enough: quoting was done like this $path = "`"C:\path\with space\to\script.ps1`""

).

This is a simplified function that I want to use 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
}

      

+3


source to share


2 answers


I solved the problem with the help of a colleague.

We went a little indirectly and included cd

in the appropriate directory and ran the command after that. It 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 fixes the error output, I hope some other people facing similar issue can use this to fix their problems.

Cheerioh and thanks for the answer!

+3


source


Try with invoke-expression but you need to check how many quotes are required



Invoke-expression "$path $param"

      

0


source







All Articles