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:

For PowerShell 4.0 and above:

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

four × two =

Close Menu