Thursday, 20 May 2010

How to supply named arguments to a PowerShell script

Calling a parameterised PowerShell script from a batch file or command window using name parameters is pretty easy, just flag each paramater name and supply a value like so:

powershell.exe "& ./MyScript.ps1 -MyParam1 'MyValue 1' –MyParam2 MyValue2"

Note I’ve wrapped MyValue1 in single quotes because of the space; the single quotes are stipped off the argument when it’s presented to the script.

MyScript.ps1 would use the parameters like so:

Param($MyParam1, $MyParam2)
write-host $MyParam1
write-host $MyParam2

The Param statement declares the formal parameters accepted by the script and must be the first executable line of code in the script. The parameters can now be used like any other variable, as demonstrated by the two write-host calls.

Disclaimer: I’m a PowerShell rookie! 

No comments:

Post a comment

Spam comments will be deleted

Note: only a member of this blog may post a comment.