PowerShell #requires

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

Syntax
      #Requires -Version N[.n]
      #Requires -PSEdition [ Core | Desktop ]
      #Requires –PSSnapin PSSnapin-Name [-Version N[.n]]
      #Requires -Modules { Module-Name | Hashtable } 
      #Requires –ShellId ShellId
      #Requires -RunAsAdministrator

Key
 -Version N[.n]
      Specifies the minimum version of PowerShell that the script requires.
      Enter a major version number and optional minor version number.
      For example: 
        #Requires -Version 3.0

  -PSSnapin PSSnapin-Name [-Version N[.n]]
      Specifies a Windows PowerShell snap-in that the script requires. Enter the snap-in
      name and an optional version number.
      For example: 
        #Requires –PSSnapin DiskSnapin -Version 1.2

  -PSEdition [ Core | Desktop ]
      Ensure that a script runs only on PowerShell Core:  -PSEdition Core
      or ensure that a script runs on PowerShell Desktop: -PSEdition Desktop

  -Modules Module-Name | Hashtable  
      Specifies Windows PowerShell modules that the script requires. Enter the module
      name and an optional version number. The -Modules parameter is introduced in PowerShell 3.0.

      If the required modules are not in the current session, PowerShell imports them.
      If the modules cannot be imported, PowerShell throws a terminating error.

      For each module, type the module name (String) or a hash table
      with the following keys. The value can be a combination of strings
      and hash tables.  

          -- ModuleName. This key is required.
          -- ModuleVersion. This key is required.
          -- GUID. This key is optional.

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


  -ShellId
      Specifies the shell that the script requires. Enter the shell ID.
          
      For example,
        #Requires –ShellId MyLocalShell


  -RunAsAdministrator
      When this switch parameter is added to your requires statement, it specifies that the
      PowerShell session in which you are running the script must be started with elevated user rights 
      (Run as Administrator).
      For example,
        #Requires -RunAsAdministrator 

A script can include more than one #Requires statement.
The #Requires statements can appear on any line in a script but must be the first item on a line in a script.

Example

Run the script only in PowerShell 4 or greater:

#Requires –Version 4
# the rest of the script

“A civilization is built on what is required of men, not on that which is provided for them” ~ Antoine de Saint-Exupery

Related PowerShell Commands:

Run a script - How to run a PowerShell script.
Automatic variables - Variables created and maintained by PowerShell $_, $Args, $Error, $Home etc


 
Copyright © SS64.com 1999-2019
Some rights reserved