Home > OS >  look up user in AD using text file and export to CSV
look up user in AD using text file and export to CSV

Time:11-20

Trying to look up a user by DisplayName from a txt file and trying to export it to a CSV.

The expected goal is to have a list of LastName, FirstName (displaynames.txt), have it return an exported CSV file with the information in the "Format-Table" within the code.

Here's the code I've tried

ForEach ($DN in (Get-Content -Path c:\displaynames.txt))
{  Get-ADUser -Filter { displayName -like "*$DN*" } -SearchBase "DC=DOMAIN,DC=NET" | Format-Table Surname,GivenName,SamAccountName,UserPrincipalName | Out-File C:\UserAD.csv
}

the file returns blank. Thoughts? much appreciated in advance

CodePudding user response:

Give this a try, as Jonathan mentioned in his comment, Format-Table is meant to display formatted information to the console and, even though you can use it to export the formatted information to a file it will definitely not be a CSV.

The other potential problem on your code, is that C:\UserAD.csv is getting replaced on each iteration of the loop because Out-File doesn't have the -Append switch.

Get-Content -Path c:\displaynames.txt | ForEach-Object {
    if(-not [string]::IsNullOrWhiteSpace($_))
    {
        Get-ADUser -LDAPFilter "(displayName=*$_*)" -SearchBase "DC=NWIE,DC=NET"
    }
} | Select-Object Surname, GivenName, SamAccountName, UserPrincipalName |
Export-Csv path/to/csv.csv -NoTypeInformation
  • Related