Dictionary in Powershell on which I will iterate

Viewed 27

I want to create a dictionary, on which later on I would like to iterate. So the dictonary would look like this:

$dictionary = 
subnet |address
xyz | 10.1.2.0/24 
abc | 10.1.3.0/24
psh | 10.1.4.0/24

And i would like to iterate

foreach ($item in $dictionary){
$dmz = New-AzVirtualNetworkSubnetConfig -Name $item.subnet -AddressPrefix $item.address


}

Does anyone knows how to create such a dictionary/table? As i am not really familiar with powershell, but I would like to create a simple script

2 Answers

I'd recommend using CSV data as they are the esiest to edit by hand

$dictionary = 
@'
subnet,address
"xyz","10.1.2.0/24" 
"abc","10.1.3.0/24"
"psh","10.1.4.0/24"
'@ | 
ConvertFrom-Csv

foreach ($item in $dictionary) {
    $dmz = New-AzVirtualNetworkSubnetConfig -Name $item.subnet -AddressPrefix $item.address
}

Of course you could use a CSV file and import it with Import-CSV. This way you wouldn't need to edit the script itself. ;-)

To complement Olaf's working answer, here is an alternative way using a hashtable literal @{…}:

$dictionary = @{
    xyz = '10.1.2.0/24' 
    abc = '10.1.3.0/24'
    psh = '10.1.4.0/24'
}

foreach( $item in $dictionary.GetEnumerator() ) {
    $dmz = New-AzVirtualNetworkSubnetConfig -Name $item.key -AddressPrefix $item.value
}

Note that the enumeration doesn't necessarily happen in order. If that is import, create an ordered hashtable instead:

$dictionary = [ordered] @{
    xyz = '10.1.2.0/24' 
    abc = '10.1.3.0/24'
    psh = '10.1.4.0/24'
}
Related