Initializing arrays in PowerShell (en-US spelling for search engine purposes
).
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 stackoverflow.com 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. ![]()
Anyway. How to define or initialise (initialize) an array in PowerShell?
For example, in C# we’d do this:
Person[] p = new Person[];
or
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…