Execute powershell command with elevated rights and output error messages

The following code works. But I don’t get any error codes from the called process

Start-Process powershell.exe -Verb runas -ArgumentList "$Command" -Wait -PassThru

The following code returns the error messages from the called process. Powershell does not seem to be running elevated rights despite $oProcessInfo.Verb = “RunAs”.

$oProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$oProcessInfo.FileName = $sProcess
$oProcessInfo.Verb = "RunAs"
$oProcessInfo.RedirectStandardError = $true
$oProcessInfo.RedirectStandardOutput = $true
$oProcessInfo.UseShellExecute = $false
$oProcessInfo.Arguments = $sArgs
$oProcessInfo.CreateNoWindow = $true
$oProcess = New-Object System.Diagnostics.Process
$oProcess.StartInfo = $oProcessInfo
$oProcess.Start() | Out-Null
$oProcess.WaitForExit() | Out-Null
$sSTDOUT = $oProcess.StandardOutput.ReadToEnd()
$sSTDERR = $oProcess.StandardError.ReadToEnd()
$pOutPut.Value="Commandline: $sProcess $sArgs`r`n"
$pOutPut.Value+="STDOUT: " + $sSTDOUT + "`r`n"
$pOutPut.Value+="STDERR: " + $sSTDERR + "`r`n"

Does anyone have an idea what I’m doing wrong or how can I solve my problem?

you can use -RedirectStandardError parameter with Start-Process, it accepts a file name where it will write the error. Similarly for -RedirectStandardOutput

Can I spend that directly or do I have to go through a file export?

You could have read the help for Start-Process and simply try it. :-/

In the help I find the following:

  • Specifies a file.
  • By default, the errors are displayed in the console.
If I do not specify a parameter after -RedirectStandardOutput I get a error message, Enter a parameter of type "System.String".

If I pass a variable behind it, it will not be filled. So where is the mistake? Or, how is the Help to understand?

The combination -Verb runas and -RedirectStandardOutput C: \temp\Error.txt also results in error:

The parameter set can not be resolved with the given named parameters

I Tryed:

start-Process powershell.exe -Verb runas -ArgumentList "$Command" -Wait -PassThru -RedirectStandardOutput C:\temp\Error.txt

See this
https://stackoverflow.com/questions/7902649/get-error-and-standard-output-from-an-elevated-child-process