Home > Net >  Getting AD info using Get-ADGroupMember not working as expected
Getting AD info using Get-ADGroupMember not working as expected

Time:01-06

So i am trying to write a script that basically gets a list of AD groups, and then with each group, gets the members and memberof.

So far i have this :

Import-Module ActiveDirectory

    $groupList = get-adgroup -filter *| select-object Name | sort-object -property name

Which works fine. nice and simple. No problem. When i run write-output $groupList, it spits out the list of my AD groups. Happy days!

Then I add this :

foreach($group in $groupList){

    Get-ADGroupMember -Identity $group

So my code block looks like this :

Import-Module ActiveDirectory

$groupList = get-adgroup -filter *| select-object Name | sort-object -property name

foreach($group in $groupList){

    Get-ADGroupMember -Identity $group
}

And get this error :

Get-ADGroupMember : Cannot bind parameter 'Identity'. Cannot create object of type 
"Microsoft.ActiveDirectory.Management.ADGroup". The adapter cannot set the value of property "Name".

I have also tried this :

Get-ADGroup -filter * -Properties MemberOf | Where-Object {$_.MemberOf -ne $null} | Select-Object Name,MemberOf

Which works great in Powershell:

Image of working script results

Yet strangley, when i then add the export-csv on the end, that same error returns :

Exported-CSV image

Can someone please educate me, as no doubt its myself being a little stoopid.

Thanks.

CodePudding user response:

$groupList does not directly contain an array of strings / names.
Use the following command to get only the names:

$groupList = Get-ADGroup -Filter * | Sort-Object -Property Name | Select-Object -ExpandProperty Name

MemberOf and Members are arrays. Export-Csv does not know how to export them into a file. Here an example, how to handle this.

Get-ADGroup -Filter * -Properties MemberOf, Members | `
    Select-Object -Property Name, @{Name = 'MemberOf'; Expression = {$_.MemberOf -join ';'}}, @{Name = 'Members'; Expression = {$_.Members -join ';'}} | `
    Export-Csv -Path 'path' -NoClobber -NoTypeInformation
  •  Tags:  
  • Related