Home > Back-end >  Powershell query multidimensional hash
Powershell query multidimensional hash

Time:11-12

I'm struggling creating and querying data of an object. (I think hash table)

  • two environment (test and production)
  • two servertypes per environment (webserver and appl servers)
  • 1 or more servers of each type

I want to store the hostnames within the applicable section. I created the following hash:

$arr =@{}
    $arr.Environment = @{}
    $arr.Environment.Production = @{}
    $arr.Environment.Production.serverType = @{}
    $arr.Environment.Production.serverType.webServer = @{}
    $arr.Environment.Production.serverType.entServer = @{}

    $arr.Environment.Test = @{}
    $arr.Environment.Test.serverType = @{}
    $arr.Environment.Test.serverType.webServer = @{}
    $arr.Environment.Test.serverType.entServer = @{}

I found that I can access data like:

$serversArray.Environment.Test.serverType.webServer

I would like to know:

  1. is this the right way of doing this? are there better / easier way to accomplish this?
  2. how do I loop/filter this object, retrieving servernames that meet the specified criteria? Since I need to have 1. all test webservers then 2. all test appl servers etc

thanks

CodePudding user response:

If you're able to save all this in one go (using variables or hardcoded strings), you should be using the native format to store it - much more readable.

See

$Optiplex = @{
                'Brand' = 'Dell'
                'Model' = 'Optiplex'
                'Specs' = @{
                                'RAM' = '4 GB'
                                'CPU' = 'Intel i5'
                                'USB Ports' = '3'
                                'CD/DVD Drive' = 'No'
                                'HDD' = '320 GB - SSD'
                           } #Specs
             } #Optiplex

From this walkthrough

You'll be able to access the variables for the hashtable in the same way, such as Optiplex.Specs.RAM to get the value for RAM.

CodePudding user response:

I found following way to achieve this:

$order = @(("Test","Production"),("webServer", "entServer"))
        
foreach($env in $order[0]) {
    Write-Host "Environment: $env"
    foreach($svr in $order[1]) {
        Write-Host "ServerType: $svr"
        write-host "hostnames: "$serversArray.Environment.$($env).serverType.$($svr)
    }
}

This will loop the correct way/sequence and lists correct servers:

Environment: Test
ServerType: webServer
hostnames:  tweb1 tweb2
ServerType: appServer
hostnames:  tapp1
Environment: Production
ServerType: webServer
hostnames:  pweb1 pweb2 pweb3
ServerType: appServer
hostnames:  papp1 papp2 papp3 papp4
  • Related