PowerShell for Windows Admins

May 16 2012   1:50PM GMT

Scripting Games 2012 comments: #19 default parameters

Richard Siddaway Richard Siddaway Profile: 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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: