Search code examples
azurepowershellobject-graph

Reference a hashtable that is an object in a Powershell variable


I'm using az vm list-skus -l australiasoutheast | convertfrom-json to populate a variable (lets call it $skus) so I can use it in a PS script. When $skus is populated, it's contents look like:

apiVersions  :
capabilities : {@{name=MaxResourceVolumeMB; value=256000}, @{name=OSVhdSizeMB; value=1047552}, @{name=vCPUs; value=8}, @{name=MemoryPreservingMaintenanceSupported; value=False}…}
capacity     :
costs        :
family       : standardMSFamily
kind         :
locationInfo : {@{location=australiasoutheast; zoneDetails=System.Object[]; zones=System.Object[]}}
locations    : {australiasoutheast}
name         : Standard_M8-4ms
resourceType : virtualMachines
restrictions : {}
size         : M8-4ms
tier         : Standard

The capabilities and locatioinfo objects in the variable look like hashtables.

I can do $skus | select name, capabilities which outputs:

name                   capabilities
----                   ------------
Aligned                {@{name=MaximumPlatformFaultDomainCount; value=2}}
Classic                {@{name=MaximumPlatformFaultDomainCount; value=3}}
Premium_LRS            {@{name=MaxSizeGiB; value=4}, @{name=MinSizeGiB; value=0}, @{name=MaxIOps; value=120}, @{name=MinIOps; value=120}…}
Premium_LRS            {@{name=MaxSizeGiB; value=128}, @{name=MinSizeGiB; value=64}, @{name=MaxIOps; value=500}, @{name=MinIOps; value=500}…}
Premium_LRS            {@{name=MaxSizeGiB; value=256}, @{name=MinSizeGiB; value=128}, @{name=MaxIOps; value=1100}, @{name=MinIOps; value=1100}…}

How can I get to and extract the data I need from those hashtables?

I tried the usual select-object to try and get to it, but I can only get as far as the capabilities object, but I cannot reference anything inside that.


Solution

  • How can I get to and extract the data I need from those hashtables?

    To retrieve all capabilities from a hash table, use Select-Object to print the specific value from the capabilities parameter.

    Here is the PowerShell script to reference the value from capabilities parameter.

    $skus = az vm list-skus -l australiasoutheast | convertfrom-json
    $skus | Where-Object { $_.Capabilities -ne $null } | ForEach-Object {
        $matchingCapability = $_.Capabilities | Where-Object { $_.Name -eq "OSVhdSizeMB" -and $_.Value -eq 1047552 }
        if ($matchingCapability -ne $null) {
            $_ | Select-Object Name, @{ Name = "Capabilities"; Expression = { $matchingCapability } }
        }
    }
    

    Output:

    enter image description here

    To display all values within capabilities, you can utilize the following cmdlet to print only name and values.

      $skus | Select-Object Name, @{ Name = "Capabilities"; Expression = { $_.Capabilities | ForEach-Object { $_.Name + ": " + $_.Value } } }
    

    Output:

    enter image description here