I'd like to run an external process and capture it's command output to a variable in PowerShell. I'm currently using this:
$params = "/verify $pc /domain:hosp.uhhg.org"
start-process "netdom.exe" $params -WindowStyle Hidden -Wait
I've confirmed the command is executing but I need to capture the output into a variable. This means I can't use the -RedirectOutput because this only redirects to a file.
I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.
The raw result I got with:
If all you are trying to do is capture the output from a command, then this will work well.
I use it for changing system time, as
[timezoneinfo]::local
always produces the same information, even after you have made changes to the system. This is the only way I can validate and log the change in time zone:Meaning that I have to open a new PowerShell session to reload the system variables.
Another real-life example:
Notice that this example includes a path (which begins with an environment variable). Notice that the quotes must surround the path and the EXE file, but not the parameters!
Note: Don't forget the
&
character in front of the command, but outside of the quotes.The error output is also collected.
It took me a while to get this combination working, so I thought that I would share it.