扩展MemberOf

时间:2016-11-22 06:59:17

标签: powershell active-directory active-directory-group

目前正在处理数据保管库/安全审核系统的PowerShell脚本。

我目前在使用以下脚本时遇到一些困难

$table_user = @()
$record_user = [ordered]@{
    "ObjectGUID"         = ""
    "SamAccountName"     = ""
    "Name"               = ""
    "Surname"            = ""
    "GivenName"          = ""
    "Created"            = ""
    "Modified"           = ""
    "LastLogon"          = ""
    "Enabled"            = ""
    "Office"             = ""
    "Company"            = ""
    "Department"         = ""
    "MemberOf"           = ""
    "HomeDirectory"      = ""
}
$Users = Get-AdUser -Filter * -Properties * |
         select ObjectGUID, SamAccountName, Name, Surname, GivenName,
                @{Name='Created';Expression={$_.Created.ToString("yyyy\/MM\/dd HH:mm:ss")}},
                @{Name='Modified';Expression={$_.Modified.ToString("yyyy\/MM\/dd HH:mm:ss")}},
                @{Name="LastLogon";Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy\/MM\/dd HH:mm:ss')}},
                Enabled, Office, Company, Department, MemberOf, HomeDirectory

foreach ($user in $users) {
    $Record_User."ObjectGUID"     = $User.ObjectGUID
    $Record_User."SamAccountName" = $User.SamAccountName
    $Record_User."Name"           = $User.Name
    $Record_User."Surname"        = $User.Surname
    $Record_User."GivenName"      = $User.GivenName
    $Record_User."Created"        = $User.Created
    $Record_User."Modified"       = $User.Modified
    $Record_User."LastLogon"      = $User.LastLogon
    $Record_User."Enabled"        = $User.Enabled
    $Record_User."Office"         = $User.Office
    $Record_User."Company"        = $User.Company
    $Record_User."Department"     = $User.Department
    $Record_User."MemberOf"       = $User.MemberOf
    $Record_User."HomeDirectory"  = $User.HomeDirectory

    $objRecord = New-Object PSObject -Property $Record_User
    $table_User += $objRecord
}

我希望每行包含一个唯一的MemberOf,例如。

EXAMPLE OUTPUT

是否有人能够协助我如何分隔MemberOf群组,以便每个唯一群组在导出时都在一个单独的行上?

2 个答案:

答案 0 :(得分:3)

使用嵌套循环

ForEach ($user in $users)
{
    ForEach ($group in $user.memberOf) 
    {
        # your code to build a CSV row here
    }
}

NB。 $table_User += $objRecord速度非常慢,每次添加内容时都会对整个数组进行内存复制 - 因此速度越来越慢。使用:

$table_User = foreach (...) {}
相反,

语法来收集foreach循环的输出。

答案 1 :(得分:1)

将您的选择管道传输到ForEach-Object并使用嵌套循环复制每个MemberOf条目的对象,同时通过calculated property替换MemberOf属性。

$Users = Get-AdUser -Filter * -Properties * |
         select ... |
         ForEach-Object {
           if ($_.MemberOf) {
             foreach ($member in $_.MemberOf) {
               $_ | Select-Object -Property *,@{n='MemberOf';e={$member}} -Exclude MemberOf
             }
           } else {
             $_   # pass object without memberships as-is
           }
         }