2016-11-22 81 views
0

當前正在處理數據倉庫/安全審覈系統的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羣體?

回答

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

將您的選擇變爲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 
      } 
     }