📜 ⬆️ ⬇️

Run as administrator from the command line

Yesterday I spent some time running the script from the command line as an administrator. I needed the equivalent of right-click> "Run as administrator":



So that when you run the script appeared a request from UAC


The runas.exe utility did not suit me, because it requires explicitly specifying a username, entering a password, or using saved credentials. I didn’t even consider “third-party” utilities - I’ll make errors in the code myself, why do I need other people? :)
')
Having tried several options, I stopped at my own PowerShell script:

$ErrorActionPreference = 'Stop' $si = New-Object System.Diagnostics.ProcessStartInfo $si.FileName = $args[0] $si.Arguments = [String]::Join(' ', $args[1..($args.Count - 1)]) $si.Verb = 'RunAs' $si.UseShellExecute = $true $process = [System.Diagnostics.Process]::Start($si) # Very strange code... # But I spy it in MSBuild... # I hope these guys know what they are doing! :) $process.WaitForExit() do { [System.Threading.Thread]::Sleep(0) } while (!$process.HasExited) Exit $process.ExitCode 

In fact, this is a ShellExecuteEx () call with the lpVerb = "RunAs" parameter.

I could not use Start-Process Commanlet because when specifying the -Verb RunAs and -Wait parameters at the same time, it fails with the error:

  PS C: \ Users \ psg> Start-Process 'cmd.exe' -Verb RunAs -Wait
 Start-Process: Access is denied
 At line: 1 char: 14
 + Start-Process <<<< 'cmd.exe' -Verb RunAs -Wait
     + CategoryInfo: NotSpecified: (:) [Start-Process], Win32Exception
     + FullyQualifiedErrorId: System.ComponentModel.Win32Exception, Microsoft.PowerShell.Commands.StartProcessCommand 

However, maybe I was just looking badly, and the utility I need still exists? .. In that case, I will be happy for your comments!

Source: https://habr.com/ru/post/114201/


All Articles