What is […[]] and when should I use it?

Line Break

Author: Martin Zugec (31 Articles)

Maybe you noticed that some Powershell scripts are using [string[]] syntax – but what does it mean?

It is pretty simple – if you add [] after your type declaration ([int[]] or [boolean[]]), it means that value is array of objects of specified type.

If you simply use [array], then it is automatically translated to [object[]]:

@(1,2,3).GetType()

And when it is useful? Usually your functions don’t accept any type of input.

When you specify array of specific type, you can let Powershell decide if it can cast to object or not.

Consider following function:

Function X ([array]$Numbers) {…}

In this case, you can use X –Numbers 1,2,3, but also X –Numbers “Martin”, “Zugec”. And you code will probably fail later on.

If you use Function X([int[]]$Numbers) {…} and try to run X – Numbers “Martin”, you will get error message:

X : Cannot process argument transformation on parameter ‘Numbers’. Cannot conve
rt value "Martin" to type "System.Int32[]". Error: "Cannot convert value "Marti
n" to type "System.Int32". Error: "Input string was not in a correct format.""

Also, sometimes you cannot use [array] – especially in case of COM classes or WMI objects. One of examples is handling Citrix policies or load evaluator rules – in that case simply use [object[]] instead of [array].

Martin

Bookmark and Share
Tags »

Author:Martin Zugec
Date: Monday, 18. January 2010 13:27
Trackback: Trackback-URL Category: Scripting, Windows PowerShell

Feed for the post RSS 2.0 Comment this post

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image