Q: What is the best way of passing parameters to my Windows PowerShell script?

A: Windows PowerShell has an easy way to pass parameters. The following first line accepts a parameter with  a default value.  Param([string]$computername='savdalhv01')

If you don't want a default value but rather want to make the parameter mandatory, it can be changed to this:

Param([Parameter(Mandatory=$true)][string]$computername)

PowerShell will automatically pass the user an error if they try to run the script without the parameter, with no need for any extra coding. By default, users can also use a parameter name, which will match the name of the variable, for example:

 

<code>script.ps1 -computername <value></code>
 

 

You can set alternate aliases if you wish by also adding the [Alias('AliasName')] to the parameter.

We have a lot of FAQs on PowerShell. You might also be interested in PowerShell for managing Hyper-V and PowerShell for managing Active Directory

Please or Register to post comments.

Upcoming Training

Mastering System Center 2012

During over 6 hours of training you can join John Savill from your computer as he will walk you through the key components and capabilities of System Center 2012, what’s involved in using the components, and the benefit they can bring to your environment.

Register Now

Current Issue

May 2013 - The NameTranslate object is useful when you need to translate Active Directory object names between different formats, but it's awkward to use from PowerShell. Here's a PowerShell script that eliminates the awkwardness.

CURRENT ISSUE / ARCHIVE / SUBSCRIBE

Windows Forums

Get answers to questions, share tips, and engage with the Windows Community in our Forums.