Powershell Best Practice #21: Use #Requires statement

By | October 5, 2015

Best Practice: You should use the #Requires statement in your scripts or modules (recommended at the top of the script).

Explanation: The #Requires statement will run a script only if the prerequisites are met.

For example, you created a script using classes (PowerShell v5), using activedirectory module and administrative rights are needed.

PowerShell version : #Requires -Version 5.0

It is recommended to write PowerShell code for the oldest version possible (nowadays the latest version is 5.0 so you should try to write for 3.0 minimum).

requires-statement-powershell-version

Module : #Requires -Modules activedirectory

requires-statement-module-activedirectory

Note: The Modules parameter is available only starting from PowerShell 3

RunAsAdministrator: #Requires -RunAsAdministrator

requires-statement-runasadministrator-powershell

You can have several requirements in the same line:  #Requires -Version 3.0 -Modules ActiveDirectory, DnsClient -RunAsAdministrator

or in several lines (I prefer having that in several lines, it is clearer to read).

There is no specific order and you can put the #Requires statement where you want (here in line 2).
It is case insensitive (#REQUIRES #Requires or #requires, all work).

requires-statement-runasadministrator-powershell-order

It is much better to use #Requires statement instead of writing additional code (to check specific version, module, etc.) or custom messsages (moreover the error will be in the local language of the user).

requires-statement-runasadministrator-powershell-in-german


previous-buttonnext-button

One thought on “Powershell Best Practice #21: Use #Requires statement

  1. Paul Gordon

    Here’s a test for you… make a simple script containing nothing but the following…
    param(
    [switch]$test1 = $false,
    [switch]$test2 = $false
    )
    Save it, run it, and test the tab autocompletion for the parameters…. – works fine right?
    Now, add this 1 extra line at the end:
    #requires -modules activedirectory
    again, save & run and test autocompletion of the params… – notice anything different?
    I have tried this on 3 different machines, one’s got PoSh 2.0, the others both 5.1
    On all 3, if the module specified is activedirectory, the tab autocomplete stops working for the params… – other modules (that I’ve tried, such as msonline, azuread etc.) do NOT appear to break it… thus far the only module I’ve found that does is the aforementioned activedirectory…
    It happens in both the console and the ISE (not tested any other IDE’s).
    Weird….? A bug…? Thoughts….?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *