Powershell – Run external powershell script and capture output – Can’t pass parameters

Question:

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 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).


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:

Answer:

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:

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!

Source:

Powershell – Run external powershell script and capture output – Can’t pass parameters by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply