Reputation: 51
I tried the following code to extract the domain and it worked just fine when defining a variable
$ADS = 'CN=Lamda,OU=OU_Bloquage,DC=Adminstrateur,DC=6NLG-AD'
But things didn't go well when I changed $ADS
into
$ADS = Get-ADUser -Identity 'Lamda' -Properties DistinguishedName |
select DistinguishedName`
The result that I want to have is:
DC=Administrateur,DC=6NLG-AD`
Below is the code that I've wrote
$ADS = Get-ADUser -Identity 'Lamda' -Properties DistinguishedName |
select DistinguishedName
$pattern = '(?i)DC=\w{1,}?\b'
([RegEx]::Matches($ADS, $pattern) | ForEach-Object { $_.Value }) -join ','
Upvotes: 1
Views: 7018
Reputation: 61168
As Ansgar Wiechers and Lee_Daily already pointed out, all you really want is the DistinghuishedName property of a user.
The Get-ADUser
cmdlet returns this property by default, so to get it as string simply do:
$dn = Get-ADUser -Identity 'Lamda' | Select-Object -ExpandProperty DistinguishedName
$dn will now be a string CN=Lamda,OU=OU_Bloquage,DC=Adminstrateur,DC=6NLG-AD
To get only the part where it starts with DC=
from that string there are many options.
For instance:
$DN.Substring($dn.IndexOf("DC="))
Another way could be:
'DC=' + ($DN -split 'DC=', 2)[-1]
Or even something like this wil do it:
($DN -split '(?<![\\]),' | Where-Object { $_ -match '^DC=' }) -join ','
.. and probably a lot more ways to get the desired result
Upvotes: 1