Powershell

Marcus Oh asked me in IM today how he could tell if an object is an array. I could think of a couple of ways, but one is “more better”.

The first way is to check for the presence of the count property.

PS C:\> $a = 1,2,3
PS C:\> $a.Count
3
PS C:\> $b = "test"
PS C:\> $b.count
PS C:\>

This works, but it’s probably not the best way to do it. There could be other object types which do have a count property.

Here’s a better way:

PS C:\> $a.GetType()

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

PS C:\> $b.GetType()

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

You can check the BaseType of an object to see if it is “System.Array”. So what’s the best way to check for this in a script? You can use the –Is operator to validate object types, that’s what its for.

PS C:\> $a -is [system.array]
True

Here’s a short function to use in a script:

PS C:\> function Test-Array { if ( $Args[0] -is [system.array] ) { $true } }
PS C:\> test-array $a
True
PS C:\> test-array $b

Note that you can’t easily do this in a pipeline, because PowerShell will unwrap the array and send each element to a function or script. There are ways to handle this, but we can talk about that another time.  :)

: http://halr9000.com/article/678

2009-01-10 15:53:19

Hal, nice function, here it is with 23 less characters.

function Test-Array { $args[0] -is [array] }

2009-01-12 14:47:38

Searching on the vbscript command IsArray(), I stumbled on the Microsoft site that provides tricks for rewritting this older scripts in PowerShell.

http://www.microsoft.com/technet/scriptcenter/topics/winpsh/convert/isarray.mspx

2009-01-12 14:54:10

Eric,

Yup, I just wanted to show everyone the “long version” and to see the thinking behind why you would want to do it this way. The link you gave does the same thing as mine (and Doug’s version), but it uses a type shortcut or type accelerator to save some typing. Here’s some others:

http://blogs.msdn.com/powershell/archive/2006/07/12/663540.aspx

  • Microblog

  • Recent Posts

  • Recent Comments

  • meta

  • PowerShell Blogroll