Mark Minasi's Tech Forum
Sign up Calendar Latest Topics
 
 
 


Reply
  Author   Comment  
meloao

Senior Member
Registered:
Posts: 109
Reply with quote  #1 
I have been working on a script to get a list of all the groups a list of users are a member of.  The source file contains the samaccountname.  I am trying to get the list of groups and samaccountname on a separate line (export to csv).

It would look like this:

samaccountname |  group
tom.smith             | HR Group
tom.smith           |  Accounting Group
tom.smith           |   All Access Group
john.thomas        |   HR Group
john.thomas        |   Sales Group

---

$users = "C:\downloads\users.txt"
$outputfile = "C:\downloads\group-memership.log"

$list = Get-Content -Path $users

foreach ($user in $list) {

$groupName = Get-ADPrincipalGroupMembership $user | Select-Object -ExpandProperty name

}

 The two values that needs to be exportsed to csv are $user and $group.  A separate line for each group. 

0
cj_berlin

Avatar / Picture

Senior Member
Registered:
Posts: 420
Reply with quote  #2 
Well, you're almost there ;-) all you need is to iterate over the list of the group memberships:


$users = "C:\downloads\users.txt"
$outputfile = "C:\downloads\group-memership.log"
$list = Get-Content -Path $users
foreach ($user in $list) {
    $groupNames = Get-ADPrincipalGroupMembership $user | Select-Object -ExpandProperty name
    foreach ($groupName in $groupNames) {
        ('"{0}";"{1}"' -f $user,$groupName) | Add-Content $outputfile
    }
}

__________________
Evgenij Smirnov

My personal blog (German): http://www.it-pro-berlin.de/
My stuff on PSGallery: https://www.powershellgallery.com/profiles/it-pro-berlin.de/
0
meloao

Senior Member
Registered:
Posts: 109
Reply with quote  #3 
Worked like a charm! Thanks! :-)

I was just missing:

 '"{0}";"{1}"' -f $user,$groupName


I will do some more reading to learn more. What is that called and/or what could I search online to find out more? It's the first time I've seen that.
0
cj_berlin

Avatar / Picture

Senior Member
Registered:
Posts: 420
Reply with quote  #4 
it's the "-f format operator", doesn't have any fancy name AFAIK.

https://ss64.com/ps/syntax-f-operator.html
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators

You could have achieved the same by simple string expansion ("`"$user`";`"$groupName`"") or string concatenation ('"' + $user + '";"' + $groupName '"') but -f is way more comprehensive IMHO.


__________________
Evgenij Smirnov

My personal blog (German): http://www.it-pro-berlin.de/
My stuff on PSGallery: https://www.powershellgallery.com/profiles/it-pro-berlin.de/
0
meloao

Senior Member
Registered:
Posts: 109
Reply with quote  #5 
Thanks!
0
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Easily create a Forum Website with Website Toolbox.