Discussion:
How do I capture the output from a spawned Powershell Script?
(too old to reply)
s***@gmail.com
2015-01-30 17:35:17 UTC
Permalink
I want to run a power shell script unattended with administrator privileges. I read that to do that you need to spawn it as a secondary process with the admin privileges from a first instance of Powershell. All that works fine, except I cannot figure out how to redirect the output of the spawned process to a file. I have used various methods and nothing seems to work.

Below I have recreated a simple example that works to spawn a directory listing. How would I capture that listing to a file?

Thanks!


Test.cmd

SET ThisScriptsDirectory=c:\live\
SET MyScript=List.ps1
SET PowerShellScriptPath=%ThisScriptsDirectory%%MyScript%
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell '-NoProfile -ExecutionPolicy Bypass -File "%PowerShellScriptPath%"' -Verb RunAs}";
pause


list.ps1

dir
Marcel Müller
2015-01-30 18:38:00 UTC
Permalink
Post by s***@gmail.com
I want to run a power shell script unattended with administrator
privileges.. I read that to do that you need to spawn it as a
secondary process with the admin privileges from a first instance of
Powershell.
Right.
Post by s***@gmail.com
All that works fine, except I cannot figure out how to
redirect the output of the spawned process to a file. I have used
various methods and nothing seems to work.
You can pipe the output of the script's commands to a file.

get-childitem | out-file listing.txt

or you can use linux-style output-redirection

get-childitem >> listing.txt

where >> means "if file doesn't exist, create and write; if already
exists, append to file"

depending on what you want your privileged script to write to a file,
one of those ways should do the trick.

greetings,

marcel

Loading...