Categories

Scripting Games 2012 comments: #19 default parameters

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>