This PowerShell script will take a list of usernames from a file and export selected properties to a csv. It works great but I would like help to include the raw input from the text document, and I'm not sure how to add code to output NOMATCH into the csv for the usernames in my file that do not exist. Any help is greatly appreciated!
Import-Module ActiveDirectory
$users = ForEach ($user in $(Get-Content Usernames.txt)) {
Get-AdUser $user -Properties Name,displayname,Samaccountname,Surname,Mail,telephoneNumber,Department,Office,DistinguishedName,Enabled,Modified
}
$users |
Select-Object Name,displayname,SamAccountName,Surname,Mail,telephoneNumber,Department,Office,DistinguishedName,mail,Enabled,Modified |
Export-CSV Username_To_DisplayName.csv -NoTypeInformation
Import-Module ActiveDirectory
$users = ForEach ($user in $(Get-Content Usernames.txt)) {
try
{
Get-AdUser $user -Properties Name,displayname,Samaccountname,Surname,Mail,telephoneNumber,Department,Office,DistinguishedName,Enabled,Modified
}
catch
{
[PSCustomObject]@{ Name = $user; displayname = 'NOMATCH' }
}
}
$users |
Select-Object Name,displayname,SamAccountName,Surname,Mail,telephoneNumber,Department,Office,DistinguishedName,Enabled,Modified |
Export-CSV Username_To_DisplayName.csv -NoTypeInformation
There is a bug in your last statement, you reference 'mail' twice.
I personally execute such kind of task quite frequently, but take a slightly different approach. I don't use Export-CSV, but write my target file - which is technically just plain text - myself. This gives a much better flexibility adding exceptional content. Since CSV is somewhat cumbersome with respect to handling blanks and separator-chars within the text items I write a plain text file name.xls using a line format:
<textitem><tab><textitem><tab><textitem>...
<textitem><tab><textitem><tab><textitem>...
Excel complains at opening that this is a questionable format, but after positive confirmation it opens and displays as expected.