Scripting Games 2012 comments: #19 default parameters

I often saw scripts that did something like this

function test1 {            
 param (            
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.

This entry was posted in Powershell Basics, Scripting. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s