I have the below script that I use to periodically export the list of users in all of the OUs in AD, and it works pretty well, but 'DistinguishedName' isn't all that great to have as an output as it makes it hard to filter the output by OU. I've been looking, and it should be possible to remove the 'CN=' portion, leaving just the OUs, but scripting is my Achilles Heel and everything I've tried to add in from examples I've found has either returned strange results or blown up when run. How could the below script be modified to make the last column the Distinguished Name minus the 'CN=_______,'?
import-module ActiveDirectory
#Set the domain to search at the Server parameter. Run powershell as a user with privilieges in that domain to pass different credentials to the command.
#Searchbase is the OU you want to search. By default the command will also search all subOU's. To change this behaviour, change the searchscope parameter. Possible values: Base, onelevel, subtree
#Ignore the filter and properties parameters
$ADUserParams=@{
'Server' = 'DC01'
'Searchbase' = 'OU=Users,OU="OU2",OU=OU1,DC=Domain,DC=Local'
'Searchscope'= 'Subtree'
'Filter' = '*'
'Properties' = '*'
}
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
#This is where to change if different properties are required.
$DNList | ForEach-Object{($_ -split "," | Select-Object -Skip 1) -join ","}
$SelectParams=@{
'Property' = 'DisplayName', 'SAMAccountname', 'enabled', 'lastlogondate', 'logoncount', 'passwordlastset', 'created', 'DistinguishedName'
}
get-aduser @ADUserParams | select-object @SelectParams | @DNList | export-csv "c:\temp\userlist_test_$(get-date -f yyyy-MM-dd).csv"