1

Recently I ran into an interesting topic. I need to run a powershell command as Administrator

PowerShell.exe -NoProfile -Command "Start-Process PowerShell 
-Verb RunAs -Args $command -PassThru -Wait"

and get stdout of this command. Sadly, it gives me only process object.

I tries methods described here:

But somehow code

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ipconfig.exe"
$pinfo.Arguments = "/all"
$pinfo.CreateNoWindow = $true
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Verb = "RunAs"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

keeps ignoring $pinfo.Verb = "RunAs" string and runs as regular user. Please note, that I need to be able to run powershell commands with elevated privileges, not just programs like ping and calc.

Any ideas how to fix this? Thank you.

geoai777
  • 102
  • 1
  • 8
  • 1
    For using "RunAs" verb you need "UseShellExecute=$true". – zett42 Jul 14 '23 at 07:04
  • 1
    Good point, @zett42, but if you do that, you won't be able to use and `.RedirectStandardOutput` and `.RedirectStandardError` – mklement0 Jul 14 '23 at 15:01
  • In short: It appears that for security reasons you cannot directly capture the output streams of an elevated process, and therefore need a workaround where you call a _shell_ as the elevated process and use that shell's redirection features to save the output streams to _files_. See the linked duplicate for details. – mklement0 Jul 14 '23 at 15:03

0 Answers0