JM1
JM1

Reputation: 1715

PowerShell - Pass array as an optional parameter value

I'm pretty new to PowerShell.

I'm trying to pass an array of server names as an optional parameter value to get the last bootup time for a list of servers.

Example 1

$serverList = @('server1"', '"server2"', '"server3"', '"server4"', '"server5"')

Get-CimInstance -ComputerName $serverList -ClassName win32_operatingsystem | Select-Object csname, lastbootuptime

Example 2

Get-CimInstance -ComputerName server1,server2,server3,server4,server5 -ClassName win32_operatingsystem | Select-Object csname, lastbootuptime

I'm likely missing a key piece of fundamental knowledge as to why what I'm doing wasn't working. What am I missing?

Thanks for the help.

Upvotes: 0

Views: 179

Answers (1)

Theo
Theo

Reputation: 61148

In the first example you are over-doing things with the quotes. (also server1 has an ending double quote, but no starting double quote..)

By putting the servers inside single quotes ', the text inside it is taken literally, so you are feeding the cmdlet with names like "server2", so including the double-qoute characters.
These quotes obviously don't belong to the server name.

BTW: Not an error, but you don't need the @() when creating the server names array.

This would be a better way of setting up your string array, where you can use either single or double quote characters, but not both:

$serverList = 'server1', 'server2', 'server3', 'server4', 'server5'
Get-CimInstance -ComputerName $serverList -ClassName win32_operatingsystem | Select-Object csname, lastbootuptime

You have also noticed that when used as parameters to a cmdlet, you don't even need the quotes, and the elements are interpreted as strings, as long as they do not contain space characters:

Get-CimInstance -ComputerName server1,server2,server3,server4,server5 -ClassName win32_operatingsystem | Select-Object csname, lastbootuptime

Upvotes: 2

Related Questions