rolfderwolf
rolfderwolf

Reputation: 51

Get-ADUser - want to write only one part of the OU into a variable

I have this:

Get-ADUser myuser |
Select @{n='OU';e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}}

But I need to get only on part of the OU of a specific user which I have to define as a variable in the beginning.

I get this

OU=Users,OU=Munich,DC=xyzdom,DC=xyz

And I want to detect if the user is in the Munich OU or where ever. So the output should be just $city and the input $username

I have no clue how to do this. But I suspect it should be not as hard to achieve this goal.

Maybe someone has time and passion to show me how :)

Thank you so much Greetings

Thanks a lot for the help. (I can't use the city property.) My solution looks like this now:

Import-Module ActiveDirectory
$samaccountname = "Smith"

$ou = Get-ADUser $samaccountname | Select @{n='OU';e={$_.DistinguishedName.split(',')[-3].split("=")[-1]}} | FT -HideTableHeaders

$ou

Now, the output is just: Munich

I want to go on using this variable but maybe it's in a wrong format. when I try to use it with orchestrator I get an output like this: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData

So maybe it has to be formated as string??? How can I do that?

Upvotes: 0

Views: 764

Answers (1)

Theo
Theo

Reputation: 61068

I agree with Santiago that using the users AD attribute City would be a much better solution, but if you don't have that filled in on the users, you may try below.

A DistinguishedName can contain commas, escaped characters and even special characters converted to their HEX representation. See here and there

Simply splitting a DN on the comma can therefore return unwanted results.

For this, I've written a small helper function some time ago you could use:

function Parse-DistinghuishedName {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
        [string[]]$DistinghuishedName
    )
    begin {
        function _ReplaceSpecial([string]$value) {
            # replace all special characters formatted as BackSlash-TwoDigitHexCode
            $match = ([regex]'(?i)\\([0-9a-f]{2})').Match($value)
            while ($match.Success) {
                $value = $value -replace "\\$($match.Groups[1].Value)", [char][convert]::ToUInt16($match.Groups[1].Value, 16)
                $match = $match.NextMatch()
            } 
            # finally, replace all backslash escaped characters
            $value -replace '\\(.)', '$1'
        }
    }
    process {
        foreach ($dn in $DistinghuishedName) {
            $hash = [ordered]@{}
            # split the string into separate RDN (RelativeDistinguishedName) components
            $dn -split ',\s*(?<!\\,\s*)' | ForEach-Object {
                $name, $value = ($_ -split '=', 2).Trim()
                if (![string]::IsNullOrWhiteSpace($value)) {
                    $value = _ReplaceSpecial $value

                    switch ($name) {
                        'O'       { $hash['Organization']       = $value }
                        'L'       { $hash['City']               = $value }
                        'S'       { $hash['State']              = $value }
                        'C'       { $hash['Country']            = $value }
                        'ST'      { $hash['StateOrProvince']    = $value }
                        'UID'     { $hash['UserId']             = $value }
                        'STREET'  { $hash['Street']             = $value }
                        # these RDN's can occur multiple times, so add as arrays
                        'CN'      { $hash['Name']               += @($value) } 
                        'OU'      { $hash['OrganizationalUnit'] += @($value) }
                        'DC'      { $hash['DomainComponent']    += @($value) }
                    }
                }
            }
            $hash
        }
    }
}

It parses the DN into its RDN components and returns a Hashtable.

In your case, use it like:

(Parse-DistinghuishedName 'OU=Users,OU=Munich,DC=xyzdom,DC=xyz').OrganizationalUnit[1]  # --> Munich

Upvotes: 2

Related Questions