Need a comma to separate SamAccountName from groups

I have this script to extract users starting with the letter "m" and the groups in which they belong. The result of the script is fine, but I also need SamAccountNamegroups that should be on the same line and separated by a comma so that I can better position it in the Excel file. Any suggestions?

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
    }
}
+4
source share
2 answers

If you want all the groups for a given user on the same line as the username, you could do something like this:

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
}

or like this (using the pipeline):

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
+2
source

Just add $ user in front of the group.

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

Source: https://habr.com/ru/post/1605694/


All Articles