Using a list as a default parameter value

November 13th, 2016 by and tagged , , , ,

I got an interesting question in a comment today on my old post on Getting the Free Disk Space of Remote Computers. While I answered the comment in the original post, it brought up something that’s not well understood, so I thought I’d take a moment to give a fuller answer here, where it will be more discoverable.


The reader complained that when he ran the script without parameters, he was getting an error. When I read the error, it was clear that he had modified the script to set a default value for the ComputerName parameter that was a list of computers, rather than a single computer. A reasonable change, since the script is set to handle a list or array of strings with [string[]]. And if you use the parameter with a list of -ComputerName ‘server1′,’server2′,’server3’, etc., from the command line, it handles that list as you would expect. But if you try to set a default value for the ComputerName parameter with that same list:

Param ([Parameter(Mandatory=$False,Position=0)]
       [String[]]$ComputerName = 'server1','server2','server3')

You’ll get an error:

Missing expression after ','

So, does this mean you can’t set a default value that is a list? Of course not! But it does mean you need to let PowerShell know explicitly what you’re doing. When you pass in an adhoc list like that from the command line, it just works because PowerShell does a fair amount of magic for things it sees on the command line. But in a script, we need to be more explicit. So, instead, we need to declare our list as… A List! We do that with:

Param ([Parameter(Mandatory=$False,Position=0)]
       [String[]]$ComputerName = @('server1','server2','server3'))

Now, our script works as we’d expect. It accepts my default list of server1, server2, server3, but allows me to override that list with my own list at the command line. (And remember, a list can be a list of length one, having only a single member. )

Posted in PowerShell | Comments Off on Using a list as a default parameter value

Comments are closed.