How to powershell script ask for administrator rights

Viewed 1896

How can I do a powershell script to ask for administrator rights to the user? To open modal and accept or enter admin password. Is it possible?

2 Answers

I have written a small snippet, add it to the beginning of your script.

if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
 Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList "-File `"$($MyInvocation.MyCommand.Path)`"  `"$($MyInvocation.MyCommand.UnboundArguments)`""
 Exit
}
}

This will check if the script has elevated privileges, if not will present UAC dialog (If secure desktop is enabled, then modal dialog) to ask for administrator credentials to auto elevate.

Duplicate

You should check if you're not admin and run new process (probably with same args) but with RunAs ( means RequireElevation ) flag. Please note, that if UAC is lowered or disabled, this might not work at all.

start-process powershell –verb runAs (you can pass additional properties like $PSCommandPath)

Notes:

  • You can not to Elevate current process
  • You can not (using powershell only) run process elevated even if you have admin credentials stored in variables.
Related