使用Powershell获取所有AD用户及其组成员资格(递归)

时间:2017-07-07 18:31:16

标签: powershell active-directory powergui

我有一个以前回答的问题的脚本,但没有足够的声誉来评论。我试图运行该脚本并遇到此错误消息:

  

Export-CSV:无法将CSV内容附加到以下文件:C:\ users.csv。附加对象没有与以下列对应的属性:User; Group。要继续使用不匹配的属性,请添加-Force参数,然后重试该命令。

如何调试此脚本以解决此问题?

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 个答案:

答案 0 :(得分:0)

尝试此功能

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" }


}