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

How to easily pass parameters to Windows PowerShell scripts.

John Savill

January 1, 2013

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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:

script.ps1 -computername 

 

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

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like