arrayspowershellhashtabledsc

How do I update an array in an array in a hashtable in Powershell?


I'm using Powershell desired state configuration and have a separate definition document (psd1) I load into memory via

$ConfigData = Import-PowerShellDataFile "$Path" 

where I'd like to update the node names based on an environment variable. The overall psd1 file shows it's type as a hashtable (name and basetype are below), then allnodes shows up as an array, then nodename as another array.

Hashtable  System.Object                                                                                                 
Object[]   System.Array                                                                                                  
Object[]   System.Array   

Replace doesn't persist (like below). If I try to assign it back to itself or a copy, 'The property 'nodename' cannot be found on this object. Verify that the property exists yadda'

$ConfigData.AllNodes.NodeName -replace 'vms','vmp'
or
$ConfigDataHolder.AllNodes.NodeName = $ConfigData.AllNodes.NodeName -replace 'vms','vmp'

Direct reference/assigment doesn't persist, where below's output is still the servername previously, even in a clone scenario.

$ConfigData.AllNodes.NodeName[2] = "something"

Solution

  • A simplified example:

    $configData = @{
      AllNodes = @(
         @{
           NodeName = @(
            'Node1a', 
            'Node1b'
           ) 
         },
         @{ 
           NodeName = @(
             'Node2a',
             'Node2b'
           ) 
         }
      )
    }
    
    # OK: a specific element of *both* arrays involved - .AllNodes and .NodeName -
    #     is targeted and can therefore be assigned to.
    $configData.AllNodes[0].NodeName[1] = 'NewNode1b'