Get all AD Users and their group memberships (recursively) using Powershell

1.1k Views Asked by At

I have a script from a previously answered question, but don't have enough reputation to comment. I tried to run that script and came across this error message:

Export-CSV : Cannot append CSV content to the following file: C:\users.csv. The appended object does not have a property that corresponds to the following column: User;Group. To continue with mismatched properties, add the -Force parameter, and then retry the command.

How can I debug this script to resolve this issue?

Function Get-ADGroupsRecursive{
Param([String[]]$Groups)
Begin{
    $Results = @()
}
Process{
    ForEach($Group in $Groups){
        $Results+=$Group
        ForEach($Object in (Get-ADGroupMember $Group|?{$_.objectClass -eq "Group"})){
            $Results += Get-ADGroupsRecursive $Object
        }
    }
}
End{
    $Results | Select -Unique
}}

import-module activedirectory

$users = get-aduser -Filter {Name -Like "*"} -Searchbase "OU=Sample Accounts,DC=domain,DC=com" -Properties MemberOf | Where-Object { $_.Enabled -eq 'True' } 

$targetFile = "C:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"


foreach ($user in $users)
{
    $Groups = $User.MemberOf
    $Groups += $Groups | %{Get-ADGroupsRecursive $_}
$Groups | %{New-Object PSObject -Property @{User=$User;Group=$_}}|Export-CSV $targetfile -notype -append
}
1

There are 1 best solutions below

2
On

try this function

function Get-InChainGroups
{
    param (
        [parameter(mandatory = $true)]
        $user,
        $domain)

    $user1 = (get-aduser -filter { name -eq $user } -server $domain).distinguishedname
    Write-verbose "checking $user"
    $ldap = "(&(objectcategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648)(member:1.2.840.113556.1.4.1941:=$user1))"

    try { Get-ADobject -LDAPFilter $ldap -server $domain | select  @{ n = 'Identity'; e = { $user } }, Name, @{ n = 'DN'; e = { $_.distinguishedname } } | ft -a }
    catch { "Exception occurred" }


}