#PSTip How to prevent script execution for non-admin users

Note: This tip requires PowerShell 4.0 or above.

The #Requires statement allows us to prevent a script from running without the required elements. For example, we can specify a minimum version of PowerShell that the script requires.

#Requires -Version 3

Other elements can be a PSSnapin, Module, and a specific ShellId (see the about_Requires topic). PowerShell 4.0 added another useful prerequisite: RunAsAdministrator. When this switch parameter is added to your Requires statement, it specifies that the Windows PowerShell session in which you are running the script must be started with elevated user rights (in other words, by using the ‘Run as Administrator’ option).

The following statements require the ActiveDirectory module and elevated user rights. If the ActiveDirectory module is not in the current session, PowerShell will import it. If the module cannot be imported, PowerShell throws a terminating error. If you haven’t used “Run as Administrator” option to start your PowerShell session, you will get an error as well.

#Requires -Modules ActiveDirectory
#Requires -RunAsAdministrator
Share on: