I'm trying to write a script that will display users specific properties, Name, Mail Address, OU respectively. the output is as intended however I can't find any solution to extract and display only the user's OU detail. when I select "DistinguishedName" the response is the following pattern: {CN = X, OU = Y, DC = Z}, I want to display only the OU. iv'e tried to find a method to split the DN String however no joy so far.
Thanks in advance
Set-ExecutionPolicy Unrestricted
$filepath = "C:\Users\Administrator\Desktop\ADusers.Csv"
$searchDomain = "DC = GSDOM, DC=internal"
$adminCredential = Get-Credential
$adSrv = 'GSDC'
$session = New-PSSession -ComputerName "$adSrv" -Credential ($adminCredential)
Invoke-Command $session -Scriptblock { Import-Module ActiveDirectory }
Import-PSSession -Session $session -module ActiveDirectory
Get-ADUser -Filter * -Properties * | Select-Object "Name", "EmailAddress", "distinguishedName"
An efficient way is to derive the OU from DistinguishedName:
Get-ADUser -Filter * -Properties Mail |
Select Name,Mail,DistinguishedName,@{n='OU';e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}}
This makes use of calculated properties, which can be found at Select-Object.
-replace uses case-insensitive regex for matching. Since we did not include a replacement string, the matched text is just removed. -creplace is the case-sensitive version. See Regex for the regex breakdown.
It is not wise to use -Properties * because that is potentially a large amount of data to return from a remote server. Since you are using -Filter * also, that means you would be returning all the attributes for all users. It is very slow and resource constraining.
The OU can also be found in the CanonicalName attribute. This looks more like a Directory structure as below.
DomainName/OU1/OU2/lastname, firstname
But as it uses "/" as a separator is some what simpler to use split on if users may have a "," in their DistinguishedName.
Adding the following in should get the desired result of the last OU before the username
e@{n=OU:e={($_.CanonicalName -split "/")[-2]}}
So a query like the following
Get-Aduser -filter * -properties CanonicalName | FT Name,@{n='OU';e={($_.CanonicalName -split "/")[-2]}}
would return Lastname, Firstname OU2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With