how to run a powershell script as administrator

Here is one way of doing it, with the help of an additional icon on your desktop. I guess you could move the script someone else if you wanted to only have a single icon on your desktop.

  1. Create a shortcut to your Powershell script on your desktop
  2. Right-click the shortcut and click Properties
  3. Click the Shortcut tab
  4. Click Advanced
  5. Select Run as Administrator

You can now run the script elevated by simple double-clicking the new shortcut on your desktop.


On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script:

param([switch]$Elevated)

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

'running with full privileges'

Now, when running your script, it will call itself again and attempt to elevate privileges before running. The -elevated switch prevents it from repeating if something fails.

You may remove the -noexit switch if the terminal should automatically close when the script finishes.


if you are in the same powershell you could do this:

Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"