PowerShell for Windows Admins

Apr 10 2014   2:16PM GMT

Requires

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: