Here are a few ways to acquire (prompt for) admin privileges when using PowerShell.
1. In-Script (best way IMO, if it ALWAYS needs to run as admin):
# Get the ID and security principal of the current user account $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent() $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID) # Get the security principal for the Administrator role $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator # Check to see if we are currently running "as Administrator" if ($myWindowsPrincipal.IsInRole($adminRole)) { # We are running "as Administrator" - so change the title and background color to indicate this $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)" $Host.UI.RawUI.BackgroundColor = "DarkBlue" clear-host } else { # We are not running "as Administrator" - so relaunch as administrator # Create a new process object that starts PowerShell $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"; # Specify the current script path and name as a parameter $newProcess.Arguments = $myInvocation.MyCommand.Definition; # Indicate that the process should be elevated $newProcess.Verb = "runas"; # Start the new process [System.Diagnostics.Process]::Start($newProcess); # Exit from the current, unelevated, process exit }
NOTE: If execution policy changes are needed, replace the arguments with the following (if erroring out and closing, add “-noexit”):
$newProcess.Arguments = '-ExecutionPolicy bypass -File "' + $script:MyInvocation.MyCommand.Path + '"'
3. Within PowerShell (or another script):
Start-Process "$psHome\powershell.exe" -verb runas -ArgumentList "-file C:\scripts\script.ps1"
…also run any application as admin with this…
Start-Process cmd -verb runas
Start-Process notepad.exe -verb runas
3. With a .lnk file:
- Right Click your PowerShell script file and choose Create shortcut
- Name it as you like…
- Right-click the shortcut and click Properties
- Add powershell.exe -file at the beginning of the Target field
- Go to the Shortcut tab
- Click Advanced
- Check the Run as Administrator box
- Click OK
- Profit.