header image

Requires statement

Posted by: | April 10, 2014 | No Comment |

A comment was left on my last post stating that the requires keyword could be used to test for modules.

Requires is a keyword that can be put at the top of scripts and modules. It will prevent the script or module running if the requirement isn’t met.  You can test for a number of items. This list is for  PowerShell 4.0.  earlier versions of PowerShell have fewer options.

PowerShell version:

#Requires –version 3

This means that the code will only run on PowerShell version 3 or later

PowerShell snapin

#Requires –PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

Loads the Exchange snapin.  iIf its not available the script won’t continue.

Modules

#Requires -Modules PSWorkflow, @{ModuleName="PSScheduledJob";ModuleVersion=1.0.0.0} 

Use the module name or a hash table with name, version and optionally the GUID for the module. If the required module can’t be loaded the script fails. This is different to my test-module function as I was only interested in discovery – I wasn’t actually using the test. If your script requires a module use the #Requires statement

Elevated privileges

#Requires –RunAsAdministrator

If PowerShell isn’t running with elevated privileges the script terminates.

ShellId

#Requires –ShellId Microsoft.PowerShell   

This uses the default PowerShell Shell.  Note that the console and ISE both return Microsoft.PowerShell    when you test $shellid.  If you want to test for console vs ISE use

£> $host.name
ConsoleHost

£> $Host.Name
Windows PowerShell ISE Host

under: PowerShell Basics, PowerShell v4