Q: What is the best way of passing parameters to my Windows PowerShell script?
How to easily pass parameters to Windows PowerShell scripts.
January 1, 2013
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
You May Also Like