Search code examples
stringpowershelljoinsplitdistinguishedname

PowerShell: Split user defined distinguished name into individual parts


I have a GUI that accepts a few DNs from the user. I know how to get the text, but I can't for the life of me figure out how to split this DN up into its individual parts. The number of parts might vary. For example:

$string1 = "ou=this,ou=is,dc=a,dc=string"
$string2 = "ou=this,ou=is,ou=another,dc=dn,dc=string

What I'm trying to do is separate the ou's from the dc's and create the ou's if they don't exist. I just can't figure out how to separate the ou's from the dc's and make them into separate strings so I'll be left with:

$newString1 = "ou=this,ou=is"
$newString2 = "dc=a,dc=string"
$newString3 = "this,ou=is,ou=another"
$newString4 = "dc=dn,dc=string

I know I can split the strings by using $string1.Split(","), but I'm at a loss at this point how to store the individual values in a new variable. I'm fairly new to PowerShell, so any advice would be greatly appreciated.

I know I can create the ou's just from the information I have, but I need them separated for other work that's going to be done in the code. Would also be nice to see them split up such that I can grab the ou's individually.


Solution

  • Hopefully this is helpful in terms of what's being asked. This assumes that you want to store the relative distinguished names in two groups: those before you hit dc= and those after (and including) you hit dc=.

    $string1 = "ou=this,ou=is,dc=a,dc=string"
    $string2 = "ou=this,ou=is,ou=another,dc=dn,dc=string"
    
    foreach ($dn in $string1, $string2)
    {
        # Break the distinguished name up into a list of relative distinguished names
        $rdnList = $dn -split ',';
        $cnList = @();
        $nextIndex = 0;
    
        while ($nextIndex -lt $rdnList.Length)
        {
            $rdn = $rdnList[$nextIndex];
            $name, $value = $rdn -split '=';
    
            # Stop looping if we've hit a dc= RDN
            if ($name -eq 'dc')
            {
                break;
            }
    
            $cnList += $rdn;
            $nextIndex++;
        }
        # The remainder of the array is our RDN list
        $dcList = $rdnList[$nextIndex..($rdnList.Length - 1)];
    
        # Reassemble both lists into strings
        $cnText = $cnList -join ',';
        $dcText = $dcList -join ',';
    
        # The data has now been processed; print it out    
        Write-Host "`$dn: $dn";
        Write-Host "`$cnText: $cnText";
        Write-host "`$dcText: $dcText";
        Write-Host;
    }
    

    Output is...

    $dn: ou=this,ou=is,dc=a,dc=string
    $cnText: ou=this,ou=is
    $dcText: dc=a,dc=string
    
    $dn: ou=this,ou=is,ou=another,dc=dn,dc=string
    $cnText: ou=this,ou=is,ou=another
    $dcText: dc=dn,dc=string