Monday, June 8, 2009

How to Create a Parameter with a Set of Default Values

When you're writing a function or script that has parameters, it's easy to set a default value. Just type an equal sign (=) followed by the default value.

For example, in the MyFunction function, I create a parameter called Path and set the default value to "c:\ps-test".

function MyFunction
{
param ($path = "c:\ps-test")
...
}

But what if the default value can be more than one item? What if you can set two paths, or three names, or 10 languages as the default?

To create a parameter with more than one default value, you need to explicitly format the default value as an array "@( )" . Be sure to separate the values with commas, too.

For example, in the MyFunction function, I create a parameter called Path and set the default values to "c:\ps-test" and "c:\users\juneb".

function MyFunction
{
param ($path = @("c:\ps-test", "c:\users\juneb"))

...
}

Just to be explicit, I always show the data type in the variable, so that it shows up in the help topic for the function. To show multiple values (an array), add a pair of square brackets after the type name.

For example, the path parameter takes more than one string.

function MyFunction
{
param ([string[]]$path = @("c:\ps-test", "c:\users\juneb"))
...
}

Hope this helps!
-- juneb









How To Open Explorer from PowerShell

To open Explorer to the default directory from within PowerShell, type:

explorer

To open Explorer to a particular directory, use the Invoke-Item cmdlet.

invoke-item

- or -

ii

For example:

ii c:\ps-test
ii \\server01\juneb\sharedFiles

Then again, do you really need to open Explorer when you have PowerShell?

Enjoy!
-- juneb