Showing posts with label pipe. Show all posts
Showing posts with label pipe. Show all posts

Thursday, January 2, 2014

Get AD user groups with managers

Because we have implemented groups with managers in Active Directory, there is a need to take reports on user group memberships and also the owners of the groups the user belongs to.

I had a really long script for a while but I've got a bit better and pipe things shorter (should be a trademark), so here is my new attempt on this topic:
  1. $list = @()
  2. Get-ADUser -Filter "Name -like ""*""" -SearchBase "OU=Users,DC=contoso,DC=eu" -Properties name | % {
  3.     $name = $_.name
  4.     $_ | Get-ADPrincipalGroupMembership | % {
  5.         $line = New-Object PSObject
  6.         $line | Add-Member -MemberType NoteProperty -Name "Name" -Value $name
  7.         $line | Add-Member -MemberType NoteProperty -Name "Group" -Value $($_.name)
  8.         $line | Add-Member -MemberType NoteProperty -Name "Manager" -Value $($_ | Get-ADGroup -Properties managedBy | Select -ExpandProperty managedBy | Get-ADObject | Select -ExpandProperty Name)
  9.         $list = $list + $line
  10.     }
  11. }
  12. $list | export-csv "c:\temp\usergroups.csv" -Encoding Unicode 
Instead of 68 lines I now get things done in 10 12 lines (gave a little edit for better reports). The original script had some comments and extra stuff in it, but it wont be missed.

If anyone has good hints on creating PSObjects with many properties in one line, let me know in comments ;)