≡ Menu

How to restrict PowerShell scripts to run only from elevated PowerShell Console

Some scripts requires to be triggered from elevated powershell prompt based on what is being done in the script. In such cases, generally I use approaches like the one below. It uses a few dotnet classes to determine if the current shell is running in elevated mode or not.

$CurrentLogin = [System.Security.Principal.WindowsIdentity]::GetCurrent()            
 $secprincipal = New-Object System.Security.Principal.WindowsPrincipal($CurrentLogin)            
 $AdminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator            
 $IsAdmin=$secprincipal.IsInRole($AdminRole)            
 if(-not $IsAdmin) {            
    Write-Warning -Message "You are not running the script from 
    non elevated shell. You need elevated shell to complete the tasks in the script"            
    return            
 }            
 write-host "Staring the script execution"

While there is nothing wrong in using code like above, I came across a much nicer and easy way to do it. PowerShell has a key word called #requires which can be used to verify if the script is running from a elevated shell or not.

All you need to do is add the below line to starting of your script.

#requires -runasadministrator

So when such scripts are triggered from non elevated powershell prompt, you will see error message like below and your script execution will not start.

requires-statement-powershell

#requries has some more options using which we can verify if the shell is running a particular version of PowerShell or not and you can every verify if certain modules/snapins are imported or not.

You can get full help about requires statement by running command.

Get-Help About_requires

Thanks to PSTips from PowerShell.com for making me learn this. 🙂

Hope this help and happy learning.