Skip to main content desktop
Try Now

PowerShell Tip: Default Parameter Values

Adam RuthAdam Ruth

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?

Ready to put the PowerShell Scanner through its paces?

Take our 14-day Free Trial. Feel the power of the PowerShell scanner.
Start a Trial

Don't miss the next post!

8 ways to protect your business from ransomware

Ransomware attacks are on the rise, and it's only a matter of time before your business becomes a target. Learn how to protect yourself before it's too late.

© 2021 Corporation
  • PDQ Deploy ®
  • PDQ Inventory ®
  • SimpleMDM
  • Pricing
  • Downloads
  • Licensing
  • Buy