简体   繁体   中英

How can I redirect the error stream when calling powershell.exe using -File parameter

I'm executing a powershell script during an OS deployment task sequence using SCCM. Due to idiosyncrasies with this ecosystem I have to call the script with syntax like this (to the best of my experimentation):

powershell.exe -executionpolicy bypass -file "w:\scripts\script.ps1" -param1 "%param1%" -param2 "%param2%"

This works fine, but I wanted to capture the output of this and any error messages it throws. Normally I would do something like:

powershell.exe -executionpolicy bypass -file "w:\scripts\script.ps1" -param1 "%param1%" -param2 "%param2%" > "%logfile" 2>&1

However, per the documentation, the -file parameter must be the last parameter, and the above triggers an error since it's trying to interpret the ">" as a parameter.

Obviously I can't use:

powershell.exe -executionpolicy bypass -file "w:\scripts\script.ps1" -param1 "%param1%" -param2 "%param2%" | out-file "%logfile"

because this is a commandline engine, so even if the pipe wasn't interpreted as a parameter, out-file would be interpreted as an executable, not a cmdlet. And even if that worked, out-file doesn't capture the error stream.

Is my only option to output the script's internal logging to a file/transcript, within the script? I feel like there should be a way to do this all from the executable call. The parsing behavior of the -file parameter makes sense, but is obnoxiously limiting.

Thanks, == Matt

As noted in my comment to the question, this was apparently due to an idiosyncrasy with SCCM's task sequence engine, which somehow causes cmd /c powershell.exe to be interpreted differently than powershell.exe .

Adding the cmd /c solved the issue of > being interpreted as a -file parameter input, rather than as a stream redirection operator.

In fact, I rediscovered that I do use syntax like: powershell.exe -executionpolicy bypass -file "w:\\scripts\\script.ps1" -param1 "%param1%" -param2 "%param2%" > "%logfile" 2>&1 successfully outside of the task sequence engine, in other powershell scripts and batch scripts, so it's not a powershell nor commandline interpreter issue.

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