PowerShell: How to create an empty array!

 

Hello everyone.

I often do training or work in PowerShell, and one thing I always forget is how to create an empty array.

I usually spend some time searching the net, without luck, and always end up opening an old script, and get the code from there!

On place to start with array info is this one:

http://technet.microsoft.com/en-us/library/ee692797.aspx

It has all the info you need also how to create an empty array.

$a = @()

That’s it!

and now you can add more to it by using +=

another great tip is to always use this method when adding to an array

$user = "user info"

$array += ,$user

Notice the , in front of $user, this makes sure that even though $array might not be an array at this time (might be null if it was not initialized), we make sure that this $user string is added to a array collection, and not inserted as the value of $array.


Comments (7):

  1. Chris says:

    Outstanding, Jakob! TechNet and Et Al. (many others) have missed this glaring tip. Thanks

  2. joe.light says:

    thy 4 the short-cut 😉

  3. Matthew says:

    Exactly what I needed! Thanks!

  4. […] Gottlieb Svendsen: creating an empty array and Microsoft TechNet: even more things you can do with […]

  5. Manikandan R says:

    Thanks man.. :) This is what i was looking..

  6. Sravani says:

    You literally saved me!!

Leave a Reply