Run as Administrator in Powershell (UAC privileges elevation)
Problem
You want your script to run as administrator and prompt for it is it is not the case.
Solution
The below code should be placed at the begining of your script. It checks if the current user has administora right and re-run the script if it is not the case.
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
Source
https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.