QuickTip: Automate variable creation using New-Variable

Occasionally I get the question: “But what if I want to create fifty variables, how do I do that in PowerShell?”. My initial thought usually is: “Why?”, but seeing as there might be some scenarios in which it can be useful to batch create a large number of variables. Aside from that it is also just interesting to see how to do things like this in PowerShell.

For example if we would like to create group A-Z as empty arrays the following code can be used:

65..90 | ForEach-Object {
 New-Variable "Group$([char]$_)" -Value @()
}

Personally I would prefer creating a hash table which contains all these arrays as it is easier to work with. If you would like to automatically create a hash table that can be done in a similar manner using the following code:

65..90 | ForEach-Object -Begin {
 $HashTable = @{}
} -Process {
 $HashTable."Group$([char]$_)" = @()
}

Storing the arrays in a hash table has the advantage of having a single point of access, for example by accessing the GetEnumerator() method to display the key – value pairs that are contained in the hash table:

$HashTable.GetEnumerator()
Share

Leave a Reply

Your email address will not be published.