In a PowerShell script, how can I check if I'm running with administrator privileges?

Solution 1:

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

(from Command line safety tricks)

Solution 2:

In Powershell 4.0 you can use requires at the top of your script:

#Requires -RunAsAdministrator

Outputs:

The script 'MyScript.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.