Check if a PowerShell script is run as administrator

Sometimes, we need a script runs with admin rights, if we do not, the CMDlet that needs admin fail.

For all PowerShell versions:

# Check if powershell is launched as elevevated
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if(-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
	Write-Warning "Please run PowerShell as administrator"

For PowerShell 4.0 and above:

#Requires -RunAsAdministrator

Run scripts

If you run a non elevated PowerShell you will get the following error:

.\script.ps1 : The script ‘script.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.
At line:1 char:1
+ .\script.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (script.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresElevation

Leave a Reply

Close Menu