需要逗号将SamAccountName与组分开

时间:2015-09-03 08:35:58

标签: powershell powershell-v2.0

我有这个脚本来提取用字母" 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
    }
}

2 个答案:

答案 0 :(得分:2)

如果您希望给定用户的所有群组与用户名在同一行中,您可以执行以下操作:

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

答案 1 :(得分:0)

只需在群组前添加$ user即可。

import-module activedirectory
$file=".\atos_user_m.csv"

foreach ($suser in (get-aduser -filter {samaccountname -like "m*"})) {
    $user = $suser.samaccountName
    foreach ($group in (Get-ADPrincipalGroupMembership -Identity $user)) {
        $user + ',' + $group.SamAccountName  | out-file -filepath $file -append
    }
}