CoffeeCoder
CoffeeCoder

Reputation: 303

How to get unique departments from active directory using Powershell?

I would like to get a list of unique departments from Active Directory using PowerShell.

Current code:

Import-Module activedirectory
get-aduser -filter * -property department |select department | sort-object property -unique

This returns a list titled "department" with no data. How do I get a list of all Departments?

Upvotes: 3

Views: 24889

Answers (1)

Matt
Matt

Reputation: 46710

Your issue is solved in one of two ways

get-aduser -filter * -property department | select department | sort-object department -unique

or

get-aduser -filter * -property department | select -ExpandProperty department | sort-object  -unique

In your example you have an object with the property department. You then request that to be sorted on a property called property which does not exist.

You either use -ExpandProperty to convert the results to a string array or request sort-object to sort on the department property.

Couple of other options that will net similar results. Mileage will vary depending on your PowerShell Version.

get-aduser -filter * -property department | select -ExpandProperty department -Unique
(get-aduser -filter * -property department).department | Sort-Object -Unique

Upvotes: 8

Related Questions