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?
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?
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.
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: