Home > Back-end >  Extract domain name values from OU path powershell
Extract domain name values from OU path powershell

Time:10-22

I am extracting the OU value from a csv and getting the DC name from it

    $TOD_Data= @(Import-Csv -Path "C:\data.csv")
    $OU = $TOD_Data.oupath
    $DC = ($OU -split '(?<![\\]),' | Where-Object { $_ -match '^DC=' }) -join ','

the output I am able to extract the values like below

DC=ab,DC=if,DC=csg,DC=net

But I need to convert this value like this

ab.if.csg.net

Please let me know how can I do this

CodePudding user response:

Using the function Split-DistinguisedName in my PoshFunctions module in the Powershell Gallery you could get your answer by the following:

((Split-DistinguishedName -DistinguishedName $dn -Token | Where { $_ -match '^DC=' } ) -replace '^DC=', '' ) -join '.'

For a further sample:

$dnsample = 'CN=SampleUser,OU=users,DC=subdomain,DC=contosco,DC=com'
((Split-DistinguishedName -DistinguishedName $dnsample -Token | Where { $_ -match '^DC=' } ) -replace '^DC=', '' ) -join '.'

subdomain.contosco.com

CodePudding user response:

You could also use the function defined in this other answer which parses the DN to a hash, e.g.:

$h = $OU | Parse-DistinghuishedName 
$h.DomainComponent -join '.'

Or without an intermediate variable:

($OU | Parse-DistinghuishedName).DomainComponent -join '.'
  • Related