Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Get-ADUser to list all properties and export to .csv

Tags:

powershell

I'm trying to go through a list of users I have and would like to get a few properties (DisplayName, Office) to show in a table then convert the table to a .csv.

I've been working with:

$Users = gc "C:\scripts\Users.txt
foreach ($User in $Users) {
Get-ADUser -Identity $User -Properties DisplayName,Office
}

And that's fine, I can combine it with "select DisplayName,Office" but if I do an "Out-File -append" it just looks terrible. I think I should do this with an array or hash table but I've been reading up on them and don't really understand how I would automate one that can be exported. Thanks for any help you can provide.

like image 212
noz3r0 Avatar asked Nov 21 '14 18:11

noz3r0


2 Answers

Query all users and filter by the list from your text file:

$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
    Where-Object { $Users -contains $_.SamAccountName } |
    Select-Object DisplayName, Office |
    Export-Csv 'C:\path\to\your.csv' -NoType

Get-ADUser -Filter '*' returns all AD user accounts. This stream of user objects is then piped into a Where-Object filter, which checks for each object if its SamAccountName property is contained in the user list from your input file ($Users). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.

You can further optimize the code by replacing the -contains operator with hashtable lookups:

$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }

Get-ADUser -Filter '*' -Properties DisplayName,Office |
    Where-Object { $Users.ContainsKey($_.SamAccountName) } |
    Select-Object DisplayName, Office |
    Export-Csv 'C:\path\to\your.csv' -NoType
like image 99
Ansgar Wiechers Avatar answered Nov 04 '22 22:11

Ansgar Wiechers


This can be simplified by completely skipping the where object and the $users declaration. All you need is:

Code

get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
like image 9
Michael Blank Avatar answered Nov 04 '22 22:11

Michael Blank