Using hash tables in PowerShell and also with some Azure scenarios

If you are an IT pro who creates PowerShell scripts to improve your environment, you probably use variables to store data, which is totally acceptable when playing with relatively low-complexity scripts. But when things start getting bigger, the use of arrays and hash tables in PowerShell becomes a necessity.

In this tutorial, we are going over the few basic steps required to manage a hash table using PowerShell. It can be useful when running several loops and you want to keep the information for future use.

Since we are exploring hash tables, we will use them in a few examples with Microsoft Azure, and I hope you can see the value of this feature and add to your own scripts moving forward.

Starting with hash tables

A hash table is a key/value pair and it is really useful when used in your PowerShell scripts. In order to create a hash table, just type in the following PowerShell cmdlet.

$ErrorTable = @{}

An empty hash table starts being useful when we are able to add and remove data from or to it. Let’s add three entries to the hash table that we have just created.

$ErrorTable.Add(“Error1”,”Couldn’t be found”)
$ErrorTable.Add(“Error2”,”Second error”)
$ErrorTable.Add(“Error3”,”Third error”)

When we want to check the content of a hash table we just need to type its name, for example, $ErrorTable.

If we want to remove content from a hash table, we can use the following cmdlet, and we are going to list the content again to check if the third item was actually removed.

$ErrorTable.Remove(“Error3”)

hash tables

Retrieving data

Now that we are able to add and remove data from a hash table, our next logical step is to retrieve information, and that is useful when looking for information in your script.

If we want to retrieve the value of the entry Error01, we can use several methods. My favorites are:

$ErrorTable.Error01
$ErrorTable.Item(“Error02”)

hash tables

Retrieving keys and values

A hash table is a set of key/value pairs. We can list each one by using this short script:

$ErrorTable.Keys
$ErrorTable.Values

A common task when using PowerShell is being able to loop a hash table and retrieve the information on the keys and values — and sometimes is not that easy to use it. The following code lists the entire hash table displaying the value of the key and value columns.

ForEach ($vError in $ErrorTable.Keys){
Write-Host
Write-Host "Error Name............: " $($vError)
Write-Host "Error Value...........: " $ErrorTable[$vError]
Write-Host
}

hash tables

Time to use what we covered so far in a couple of simple scenarios to help the understanding of hash tables and start adding them to your PowerShell toolbox!

Scenario 1: Creating a report of Key Vaults per location in your subscription

Keep in mind that PowerShell is powerful and there are so many ways to get to the same result. I will try to show up a couple of different ways to get the same info, and you probably will find better and more efficient ways after a while (if you do so, please comment here to share with the rest of the community!)

Let’s say that we want a report on how many Key Vaults we have in our current subscription per region. I can think of several ways to find out that information. My first choice would be to list Key Vault per region and count the entries and that would give me the result, it would be a couple of cmdlets, as follows:

Get-AzureRMKeyVault | Group-Object Location

hash tables

Another option is to use count — however, this will require a line for each location. Here is the cmdlet to find out the number of Key Vaults in a single location.

(Get-AzureRMKeyVault | Where-Object { $_.location -eq “CanadaCentral” }).count

hash tables

All those options above are valid (my favorite is the first one because I’m lazy!). But we could get the same results using hash tables — which, of course, is the topic of this article. We could use the code below and we would be listing all Key Vaults, and for each Key Vault we will create a new key/value pair or update an existent one.

$KVList = @{}
Get-AzureRmKeyVault | % { if (!($KVList.item($_.Location))){ $KVList.Add($_.Location,1) }Else{ $KvList.Item($_.location) = $kvlist.Item($_.location) + 1 } }
$KVList

hash tables

Scenario 2: Checking permissions in a Key Vault

In the previous example, we used hash tables to demonstrate how to get the same results using different methods. I see a useful resource to use hash tables to track errors or when we need to validate certain conditions. A good example would be creating a report of all Key Vaults and check if the current account has permissions to list Secrets/Key/Certificates.

Using the following code below, we create a hash tables called $KVPermissionReport and we try to list the Secrets of all Key Vault available, for every single Key Vault we will log a success or fail. The results of this operation can be seen in the image depicted below.

$KVPermissionReport = @{}
Get-AzureRmKeyVault | % {
$vList = Get-AzureKeyVaultSecret -VaultName $_.VaultName -ErrorVariable vtmp -ErrorAction SilentlyContinue
if ($vtmp){
$KVPermissionReport.Add($_.VaultName,"Permissions Error")
}Else{
$KVPermissionReport.Add($_.VaultName,"Okay")
}
}

hash tables
OK, you now have another tool in your admin toolbox!

Featured image: Pexels

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top