Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

powershell - Change the script to export Groups and nested objects differently

I created a similiar script like that:

$Groups = Get-QADGroup 
$Result = @()
$Groups | ForEach-Object {
    $Group = $_
    $Members = Get-QADGroupMember $Group -Indirect | ? objectClass -eq "user"
    $Obj = '' | Select-Object -Property Name, Members 
    $Obj.Name = $Group.Name
    $Obj.Members = ($Members | % {$_.SamAccountName + "_" + 'Test'})
    $Result += $Obj
}
$Result | Export-Csv -Path C:Tempgroups.csv -NoTypeInformation -Encoding Unicode -Delimiter ";"

The output looks something like this (example data):

"Name";"Members"
"RootGroup01";"Subuser01_Test";"Subuser02_Test";"Subuser03_Test"
"RootGroup02";"Subuser02_Test"
"RootGroup03";"Subuser01_Test";"Subuser02_Test";"Subuser04_Test"; 

Is it possible to change the script, that I get something like this?:

"RootGroup01";"RootGroup02";"RootGroup03"
"Subuser01_Test";"Subuser02_Test";"Subuser01_Test"
"Subuser02_Test";;"Subuser02_Test"
"Subuser03_Test";;"Subuser04_Test"

The group names should be the header and the belonging users are in the right column. If there is no user, the column cell just stays empty.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can write such function to transpose your data:

function Transpose-Data{
    param(
        [String[]]$Names,
        [Object[][]]$Data
    )
    for($i = 0;; ++$i){
        $Props = [ordered]@{}
        for($j = 0; $j -lt $Data.Length; ++$j){
            if($i -lt $Data[$j].Length){
                $Props.Add($Names[$j], $Data[$j][$i])
            }
        }
        if(!$Props.get_Count()){
            break
        }
        [PSCustomObject]$Props
    }
}

Then you invoke it in the following way:

$Groups = @(Get-QADGroup)
$Members = @(
    $Groups | ForEach-Object {
        ,@(
            Get-QADGroupMember $_ -Indirect |
            ? objectClass -eq user |
            % {$_.SamAccountName + "_" + 'Test'}
        )
    }
)
Transpose-Data $Groups.Name $Members |
Export-Csv -Path C:Tempgroups.csv -NoTypeInformation -Encoding Unicode -Delimiter ";"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...