Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading