我有这个脚本来提取以字母“m”开头的用户以及他们所属的组.脚本的结果是正常的,但我需要SamAccountName和组在同一行,并用逗号分隔,以便我可以在Excel文件中更好地安排它.有什么建议?
Import-Module activedirectory
$file=".\atos_user_m.csv"
foreach ($suser in (Get-ADUser -Filter {samaccountname -like "m*"})) {
$user = $suser.SamAccountName
echo "`r`n"$user"`r`n" | Out-File $file -Append
foreach ($group in (Get-ADPrincipalGroupMembership -Identity $user)) {
$group.SamAccountName | Out-File $file -Append
}
}
最佳答案 如果您希望给定用户的所有组与用户名在同一行中,您可以执行以下操作:
foreach ($suser in (Get-ADUser -Filter {samaccountname -like "m*"})) {
$user = $suser.SamAccountName
$groups = Get-ADPrincipalGroupMembership -Identity $user |
Select-Object -Expand SamAccountName
'{0},{1}' -f $user, ($groups -join ',') | Out-File $file -Append
}
或者像这样(使用管道):
Get-ADUser -Filter {samaccountname -like "m*"} | ForEach-Object {
$groups = Get-ADPrincipalGroupMembership -Identity $_.SamAccountName |
Select-Object -Expand SamAccountName
'{0},{1}' -f $_.SamAccountName, ($groups -join ',')
} | Out-File $file