更改脚本以不同方式导出组和嵌套对象

时间:2015-11-11 11:26:44

标签: powershell

我创建了一个类似的脚本:

$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:\Temp\groups.csv -NoTypeInformation -Encoding Unicode -Delimiter ";"

输出看起来像这样(示例数据):

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

是否可以更改脚本,我得到类似的东西?:

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

组名称应​​为标题,所属用户位于右列。如果没有用户,则列单元格保持为空。

1 个答案:

答案 0 :(得分:2)

您可以编写此类函数来转置数据:

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

然后按以下方式调用它:

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