Enforce PreRequisites match before running PowerShell scripts

Many a times, you would write a script, have it happily running on your machine, share it with someone and get a call from them only to find that your script is not functioning! We all have ran into this situation once or more in our life. Some people would avoid it by writing lengthy documentation. But who reads documentation any more. So you would go to their desk and solve it for them. To overcome this problem, Microsoft has added #Requires statement in PowerShell.

The #Requires statement prevents a script from running unless the Windows PowerShell version, modules, snap-ins, and module and snap-in version prerequisites are met. If the prerequisites are not met, Windows PowerShell does not run the script. 

In this blog post, we shall discuss the use of #Requires statement. The first rule to remember is that the #Requires statement must be first item on a line in a script.

Let’s start with something as simple as version of PowerShell. Suppose, you have written a script which requires specific PowerShell version features say 5.0. We can then add a line to our script like below:

#Requires -Version 5.0

Now, let’s save the script and try to run it on a system with PowerShell 4.0. You would be greeted with below error:

Enforce PowerShell version for your scripts

The error message clearly indicates that you need to have PowerShell version 5.0 installed for the script. It also mentions current version of PowerShell.

We can use the same for adding snap-ins. Let’s say that you wrote a script for Microsoft SharePoint which requires Microsoft.SharePoint.Snapin to be loaded. We can enforce the rule in our script by:

#Requires -PSSnapin Microsoft.SharePoint.PowerShell -Version 3.0

The version number above is version of PSSnapin and is optional. So, if PowerShell fails to load the snap-in, the error message would be like:


We also combine two or more #Requires statement each in a separate line, like below:

#Requires -Modules PSWorkflow 
#Requires -Version 3

Below is the Syntax for #Requires statement:

#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -ShellId <ShellId>
#Requires -RunAsAdministrator

These all options are very useful to have and included in the script. More details on these options can be found in this MSDN article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s