May 16 2012 1:50PM GMT
Posted by: Richard Siddaway
PowerShell
Scripting Games 2012 comments: #19 default parameters
Posted by: Richard Siddaway
I often saw scripts that did something like this
function test1 { param ( [string]$computername ) if (!$computername){ $computername = $env:COMPUTERNAME } Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computername }
A function, or script, defines a parameter. The first thing the function does it test the value of the parameter and if it doesn’t exist it sets it to a default value.
No, no, no – you are making work for yourself.
Get PowerShell to do the work for you
function test2 { param ( [string]$computername = $env:COMPUTERNAME ) Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computername }
See the difference?
The parameter definition now contains a default value. If you don’t specify the parameter and a value the default kicks in and the function works.
Cuts down typing and gets PowerShell to do the work.




