Home > Blockchain >  How do I reverse transversal in a PowerShell array
How do I reverse transversal in a PowerShell array

Time:04-19

Given a PowerShell array hashtable1 similar to the following:

$dept= @{
     'Sales' = @{
        'SAM' = 'Manager'
        'SAP' = 'Person'
    }
    'IT' = @{
        'ITM' = 'Manager'
        'ITS' = 'Specialist'
        'ITT' = 'Technician'
        'ITC' = 'Consultant'     
    }
}

If enter the following in the console:

$dept.it.itc
$dept.sales.sam

I get:

Consultant
Manager

Which is as expected.

However, what I'd like to do is something like

write-host $dept.itc
write-host $dept.sam

and get

IT Consultant
Sales Manager

in return.

I'm looking for a sort function to do a 'reverse traversal' of the array because 'IT', 'Sales' etc are the OU's I need to put new users into. There are many more OU's that I have removed for brevity.


[1] An array is simply a list of values and a hashtable is a collection of key/value pairs similiar to Javascript's JSON or Python's dict.

CodePudding user response:

It is worth noting that your object is not an Array. In PowerShell @{} is a Hashtable. You can read more about working with Hashtables here.

If you have what I am going to call a unique Role Code for each role in your department OU's, all you want to do is match the Key in the nested Hashtables to find your department. It's easiest to create a quick helper function to deal with multiple calls, unless you are just looping through an array or list of strings.

Here is an example of how to extract the string you want: (If you do not have unique keys, then you may need to add additional filtering)

$Departments = @{
    'Sales' = @{
        'SAM' = 'Manager'
        'SAP' = 'Person'
    }
    'IT'    = @{
        'ITM' = 'Manager'
        'ITS' = 'Specialist'
        'ITT' = 'Technician'
        'ITC' = 'Consultant'     
    }
}

function Get-DepartmentOU {
    Param (
        [CmdletBinding()]
        [Parameter(Mandatory = $true)]
        [System.String]
        $RoleCode
    )

    # Get the DictionaryEntry in the main Hashtable where the nested Hashtable value matches the role you are looking for.
    $Department = $script:Departments.GetEnumerator() | Where-Object { $_.Value.ContainsKey($RoleCode) }
    
    # Print the name of the DictionaryEntry (Your department) and retrieve the value from the Hashtable for the role.
    Write-Output ("{0} {1}" -f $Department.Name, $Department.Value[$RoleCode])
}

And then you can get them by running the function and specifying the code.

PS > Get-DepartmentOU -RoleCode ITC
IT Consultant
  • Related