Initialising arrays in PowerShell

Initializing arrays in PowerShell (en-US spelling for search engine purposes Smile).

I think it’s taken me three years to work this out and it took a rushed script with a typo to figure it out.  Later I finally found the answer on but by then it was too late…could have made my life easier when trying to write some simple base 64 conversion code for a colleague last year.  Smile

Anyway.  How to define or initialise (initialize) an array in PowerShell?

For example, in C# we’d do this:

Person[] p = new Person[];


DirectoryAttribute[] d = new DirectoryAttribute[5];

How do we do this in PowerShell?  In much the same way, except we use New-Object in place of new and we don’t stipulate the upper bound in the square brackets but instead next to the square brackets, e.g.

[String[]]$str = New-Object String[] 5;

Or, seeing as I was using System.DirectoryServices.Protocols.DirectoryAttribute…

[System.DirectoryServices.Protocols.DirectoryAttribute]$dsa = `
    New-Object System.DirectoryServices.Protocols.DirectoryAttribute[] 10;

Simple yet hugely helpful I hope.  Happy initialising…


About Paul Williams

IT consultant working for Microsoft specialising in Identity Management and Directory Services.
This entry was posted in Scripting and tagged , , . 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s