我正在尝试使用Export-Csv
将用户名和用户的(特定组的)组成员身份导出到CSV文件。但是,我无法使用几种方法来完成此操作。
我当前的脚本运行良好,但输出仅在PowerShell控制台上显示:
$accounts = Get-Content "C:\Scripts\getUserGroups\users.txt"
foreach ($account in $accounts) {
"$account member of:"
Get-ADPrincipalGroupMembership -Identity $account |
select Name |
Where-Object { $_.name -like 'Browsing_Group*' } |
Sort Name
}
我想按有序方式将其导出到文件中
UserName1 group membership UserName2 group membership etc...
我尝试添加到变量中,但可能没有正确执行此操作:
$ArrList = [System.Collections.ArrayList]@()
$accounts = Get-Content "C:\Scripts\getUserGroups\users.txt"
foreach ($account in $accounts) {
$ArrList.Add($account)
$groups = Get-ADPrincipalGroupMembership -Identity $account |
select Name |
Where-Object {$_.name -like 'Browsing_group*' } |
Sort Name
$ArrList.Add($grops)
}
可能是另一种方法。
答案 0 :(得分:1)
您需要构建自定义对象,以便通过Export-Csv
将数据导出到CSV。这样做的2种主要方法是:
$accounts |
Select-Object @{n='Username';e={$_}}, @{n='Groups';e={
(Get-ADPrincipalGroupMembership -Identity $_ |
Select-Object -Expand Name |
Where-Object {$_ -like 'Browsing_group*' } |
Sort-Object) -join ';'
}} |
Export-Csv 'C:\path\to\output.csv' -NoType
直接构建自定义对象:
$accounts | ForEach-Object {
$groups = Get-ADPrincipalGroupMembership -Identity $_ |
Select-Object -Expand Name |
Where-Object {$_ -like 'Browsing_group*' } |
Sort-Object
New-Object -Type PSObject -Property @{
'Username' = $_
'Groups' = $groups -join ';'
}
} | Export-Csv 'C:\path\to\output.csv' -NoType
在PowerShell版本3或更高版本中,您可以将New-Object
替换为[PSCustomObject]
类型的加速器:
[PSCustomObject]@{
'Username' = $_
'Groups' = $groups -join ';'
}