Active Directory Users export to csv from multiple OUs including the OU it came from and formatting the UserPrincipalName

I'm relatively new to Powershell and im trying to write a script to export disabled users to csv. I found a Script and am trying to modify it to also save the OU it found the user in and to exclude the Domain extension from the UserPrincipalName. The AD I "inherited" at my new job is a real mess but sadly just burning it down and starting over isn't exactly an option.

the Variable "ou" doesn't seem to be what im looking for as it just saves "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection" instead of the actual ou name for each user. I've also thought about just having it find out the ou by using the $OU variable from above but i can'T seem to figure out how to convert is to just text so it just produces errors.  

As for excluding the 2 different "@domain.local"'s from the UserPrincipalName I've only ever added something to a String in Powershell and not removed. I assume I'd need to include a Regex and change the UserPrincipalName variable to be itself without "@*.*".  I'm unsure how to go about doing this so that it still saves it like the other data without interruptiong the CSV formatting.

$OUS = "OU=B,OU=DomainUsers,DC=Domain,DC=local","OU=Laufwerk_1,OU=B,OU=DomainUsers,DC=Domain,DC=local"

$result1 = 
foreach($OU in $OUS){
    Get-AdUser -filter "enabled -eq 'false'" -SearchBase $OU -Properties DisplayName,GivenName,sn,Mail,Description,LastLogonDate,UserPrincipalName,ou | 
    select-object DisplayName,GivenName,sn,Mail,Description,LastLogonDate,UserPrincipalName,ou
    }

$result1 | export-csv "C:\Users\User\Documents\DomainUsers.csv" -NoTypeInformation

Parents
  • Did Some more digging apparently i completely missed that i can output the SamAccountName instead of the UserPrincipalName and the DistinguishedName istead of the ou and would just have to cut out the "CN=*," at the beginning and the "DC=domain,DC=local" the same way i want to cut out the domain from the user principal name. So i guess my only Question left is how to format datastrings before they are save to the csv to fit my needs. 

Reply
  • Did Some more digging apparently i completely missed that i can output the SamAccountName instead of the UserPrincipalName and the DistinguishedName istead of the ou and would just have to cut out the "CN=*," at the beginning and the "DC=domain,DC=local" the same way i want to cut out the domain from the user principal name. So i guess my only Question left is how to format datastrings before they are save to the csv to fit my needs. 

Children
No Data