Strings and collections

A question on the forum brought up a point that often confuses PowerShell novices.

QUESTION: What’s the difference between

$computers = ‘W12R2SUS, W12R2DSC’


$computers = ‘W12R2SUS’, ‘W12R2DSC’


The first is a string

PS> $computers.GetType() | ft -a

IsPublic IsSerial Name   BaseType
——– ——– —-   ——–
True     True     String System.Object


The second is an array – a collection of strings

PS> $computers.GetType() | ft -a

IsPublic IsSerial Name     BaseType
——– ——– —-     ——–
True     True     Object[] System.Array

The difference is important when you try to use $computers as the value for a parameter where you want to supply a list of computer names:

if you use the string – you’ll get an error

PS> $computers = ‘W12R2SUS, W12R2DSC’
PS> $ps = New-PSSession -ComputerName $computers
New-PSSession : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri
parameter, or pass URI objects instead of strings.
At line:1 char:7
+ $ps = New-PSSession -ComputerName $computers
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.String[]:String[]) [New-PSSession], ArgumentException
    + FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.NewPSSessionCommand


You have to use an array

PS> $computers = ‘W12R2SUS’, ‘W12R2DSC’
PS> $ps = New-PSSession -ComputerName $computers
PS> $ps

Id Name            ComputerName    State         ConfigurationName     Availability
— —-            ————    —–         —————–     ————
  2 Session2        W12R2DSC        Opened        Microsoft.PowerShell     Available
  1 Session1        W12R2SUS        Opened        Microsoft.PowerShell     Available

A trap that everyone falls into at some time or other but one that can be avoided

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s