Scripting Tips & Tricks: RegEx for OU Name & Path

I 'borrowed' this RegEx off my esteemed colleague, Mr Raimund Andree, whilst working on site with him.

 

 
$pattern = '(..=)(?<Name>.*?)(?<!\\),(?<Path>.*)'

 

You can use this pattern to match the 'Name' of the OU and its parent 'Path' into named groups with those exact same names.

 

 
$a = "OU=TEST,DC=Halo,DC=net","OU=BATCH1,OU=TEST,DC=Halo,DC=net","OU=BATCH2,OU=TEST,DC=Halo,DC=net","OU=BATCH3,OU=TEST,DC=Halo,DC=net"


foreach ($b in $a) {


    $c = $b -match $pattern

    Write-Output "OU Name: $($matches["Name"])"
    Write-Output "OU Path: $($matches["Path"])"
    Write-Output " "

}

 

 

The results of the Get-ADOrganizationalUnit cmdlet could be assigned to $a