TheJanitor
TheJanitor

Reputation: 125

import-csv, get-aduser, then export-csv to filter out non-existing AD users

Import-Csv C:\username.csv | 
ForEach-Object (Get-ADUser $_.Username -Properties displayname | 
Export-Csv C:\usernames.csv

I have an old fileserver (2k3) with a bunch of homefolders. I exported a csv with get-childitem for the directories. I was going to use the name of the folder, which is mirrored to the AD username, to query AD with Get-ADUser. If AD user does not exist, then filter out those non existing users and export-csv the "active" ad users. The exported CSV would then be used in my script to migrate "active" homefolders to new homefolder VM. I have used the above code unsuccessfully. Any input would be helpful.

Upvotes: 1

Views: 8924

Answers (2)

McKenning
McKenning

Reputation: 641

briantist is correct about the curly braces.

To expand a little on his answer, you want to also include the -NoType parameter to the Export-CSV statement so the resulting CSV doesn't have a type line at the top. This makes it easier to manipulate with Excel and to feed into other PowerShell scripts!

I've put it all together for you in a single line.

Import-Csv C:\username.csv | ForEach-Object {Get-ADUser $_.Username -Properties displayname} | Export-Csv C:\usernames.csv -Notype

This tested as expected in my test lab with Windows 2012 R2.

One additional question: If your goal is to get a list of "active" AD users so you only migrate needed folders, then do you want all the info from the export? It sounds like you just need the username. Let me know and I can adjust the code for you.

EDIT: Here is the revised code to just get the list of usernames that are valid from a the CSV file as an import. I've also included code to use just a list of usernames as input in case you end up using that.

With the original CSV file as input:

Import-CSV C:\username.csv | ForEach-Object {Get-ADUser $_.username -Properties *} | select -expand SAMAccountName | Out-File C:\usernames.txt

With just a list of usernames as input:

Get-Content C:\username.txt | ForEach-Object {Get-ADUser $_ -Properties *} | select -expand SAMAccountName | Out-File C:\usernames.txt

Notice the distinction in the $_ pipeline input. One calls for a property (because it is an array of properties) and the other just calls for the whole variable (because it is a single entry).

Anyway, hope that helps!

Upvotes: 1

briantist
briantist

Reputation: 47792

I've reformatted your code a bit, without changing the meaning. I think you may have copy/pasted incorrectly.

ForEach-Object takes a [ScriptBlock] (denoted by curly braces { }):

You have used a parenthesis ( without a closing one ).

You should have:

ForEach-Object { Get-ADUser $_.Username -Properties displayname }

Upvotes: 3

Related Questions