PowerShell tip: Default parameter values

smiling man
Adam Ruth|September 17, 2010
Generic blog header
Generic blog header

If you’ve spent any time working with PowerShell you’ve probably built a function or two. Function parameters are a handy way to make general purpose functions that can be used in a number of different ways. Consider, for example, that you have a function that restarts a service that, for whatever reason, is misbehaving. You could have this:

function RestartService($name) { net stop $name net start $name }

Sometimes you need to add a sleep between the start and stop to make sure that the service comes back up correctly, but you don’t want to make a new function (one that sleeps and one that doesn’t) so you add a new parameter.

function RestartService($name, $sleep) { net stop $name sleep $sleep net start $name }

This works great, except now you have to pass in a 0 most of the time, and only use the sleep parameter on those rare occasions. To fix this, you can make the $sleep parameter default to 0 so that if you omit it you don’t get a sleep.

function RestartService($name, $sleep = 0) { net stop $name sleep $sleep net start $name }

This will give you the flexibility you need.

# Don't sleep RestartService SomeService # Sleep for 10 seconds before restarting RestartService SomeService 10

Did you know that PDQ Deploy has a PowerShell step you can use to deploy your scripts?

smiling man
Adam Ruth

Adam is a co-founders of PDQ.

Related Articles