PDQ.com mobilePDQ.com desktop
Support

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?


This blog post is part of a series on PowerShell:

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!

Using PowerShell to Install Printers

When installing printers, we will need to do the four things; Add Driver to the Store, Install the Driver, Create Printer Port, and Install the Printer