Home > OS >  I have a list of Display names that I would like to also display SAM Account Names
I have a list of Display names that I would like to also display SAM Account Names

Time:11-08

I have an application that has never had old users cleaned out of it. I exported all the LastName, FirstName to a .CSV, but would like to have it add the SAM Account Name as well. This is so I know whether the person even still exists in the company. The below script works perfectly, but...if there is no existing SAM name, it doesn't bother to include the display name. I would like to have the field called SamAccountName just put in some text like "To be removed" if there is no matching AD account. I sure it's a simple conditional check, but my PowerShell game is weak.

Import-Csv c:\temp\DisplayName.csv | ForEach {
   Get-ADUser -Filter "DisplayName -eq '$($_.DisplayName)'" -Properties Name, SamAccountName, Company | 
Select Name, SamAccountName, Company
} | Export-CSV -path C:\temp\SamAccountName.csv -NoTypeInformation

CodePudding user response:

You can use a calculated property for that. That way you pass everything from the original CSV, and just add in the samaccountname you want.

Import-Csv c:\temp\DisplayName.csv | Select *,@{l='samAccountName';e={Get-ADUser -Filter "DisplayName -eq '$($_.DisplayName)'" -Properties Name, SamAccountName, Company | Select -Expand SamAccountName}} | Export-CSV -path C:\temp\SamAccountName.csv -NoTypeInformation
  • Related