Understanding the different array types in PowerShell is essential for efficient data management and automation in your scripting endeavors.
So far, all array types havent been specific, allowing you to store "anything." For added efficiency and data integrity, you can also use typed arrays.
To create a typed array, simply specify the desired type and add []. This creates an array that can only store values of that type. Note how floating-point values are automatically converted to whole numbers:
PS> [int[]]$id = 1,2,3,4,5.1,6.3,7PS> $id 1234567
This example uses a [string[]]: a user can enter ten names, and if a number is accidentally added, PowerShell will automatically convert it to a string:
# new empty string array[string[]]$names = @()# let user enter 10 namesfor ($x=1; $x-le10;$x++){ $names += Read-Host -Prompt "Enter $x. Name"}$names.Count
Whats most important about the last example is the reappearance of the dreaded += problem we previously discussed: how can you use a typed array that can dynamically grow or shrink? [System.Collections.ArrayList] is not typed.
The solution lies in generic lists, which are very simple to use. Simply take [System.Collections.Generic.List[XXX]] and replace XXX with the type you want to use. This gives you a typed array that can grow or shrink:
PS> $list = [System.Collections.Generic.List[string]]::new()PS> $list.IsFixedSizeFalse
The example above can now be rewritten to avoid using +=. Keep in mind that this example is meant to illustrate the issue; with just 10 iterations, as shown here, you could likely get away with using +=. However, remember the examples from the previous section where += would hang Windows PowerShell.
Here is the rewritten example using a generic list:
# new empty string array[System.Collections.Generic.List[string]]$names = [System.Collections.Generic.List[string]]::new()# let user enter 10 namesfor ($x=1; $x-le10;$x++){ $userinput = Read-Host -Prompt "Enter $x. Name" $names.Add($userinput)}$names.Count
Notice that generic lists do not return anything when you add new data. Unlike [System.Collections.ArrayList], there is no need to assign the result to $null this time.
Generic lists also support all the useful PowerShell array tricks discussed in the first part of this series:
PS> $names[0,1,-2,-1]HennyFrankAlexTobi
Your ultimate PowerShell Cheat Sheet
Unleash the full potential of PowerShell with our handy poster. Whether you're a beginner or a seasoned pro, this cheat sheet is designed to be your go-to resource for the most important and commonly used cmdlets.The poster is available for download and in paper form.
Related links
- ScriptRunner ActionPacks provide ready-to-use PowerShell scripts.
- Try out ScriptRunner here
- ScriptRunner: Book a demo with our product experts