Requiring Administrator Privileges

by Jan 22, 2015

PowerShell 4.0 and later

If you know that a given script needs Administrator privileges, then a simple #requires statement is enough to make sure the requirement is met:

#requires -version 4.0
#requires –runasadministrator


'I am Admin!' 

If the script is launched without Administrator privileges, it will display a meaningful error message, explaining why it cannot run.

Actually, in the sample you see two #requires statements. The first one makes sure the script runs at least in PowerShell 4.0, which is the prerequisite for the second #requires; it was introduced in PowerShell 4.0 and would not work in older PowerShell versions.

So better not use this technique if your scripts is to target PowerShell 3.0 or older. For these scenarios, you would still need to manually check whether the script currently has Administrator privileges or not.

Twitter This Tip! ReTweet this Tip!