Running a command as Administrator using PowerShell?
If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell
with the Run as Administrator option :
PS> Start-Process powershell -Verb runAs
Microsoft Docs: Start-Process
Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).