powershell 扩展成员

cygmwpex  于 2023-05-22  发布在  Shell
关注(0)|答案(2)|浏览(209)

目前正在为数据库/安全审计系统编写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,例如;

有人能帮助我如何分离MemberOf组,以便导出时每个唯一的组都在单独的行上吗?

jk9hmnmh

jk9hmnmh1#

使用嵌套循环

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

注意:$table_User += $objRecord非常慢,每次你添加一些东西时,它都会复制整个数组的内存-所以它会越来越慢。用途:

$table_User = foreach (...) {}

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

mbjcgjjk

mbjcgjjk2#

将您的选择导入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
           }
         }

相关问题