I want to create a powershell script that checks a users profile which security groups the user belongs to inside the active directory. Then I want to write it to a file. I'm having trouble solving this problem.

Example of the expected output.

User1

Security Groups

Domain users Domain admins...

User2

Security Groups

Domain users Enterprise admins

New-Item "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"

$users = @("User1", "User2", "User3", "User4")

foreach ($user in $users){
Get-ADPrincipalGroupMembership $user | sort name | select name | Out-File "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
}

2 Answers

1
Community On Best Solutions

I imagine you could get a bit more creative with it but this could definitely work for you:

$users = @("user1","user2")

foreach ($user in $users){

    $groups = Get-ADPrincipalGroupMembership $user | Where-Object {$_.GroupCategory -eq "Security"} | Sort-Object Name | Select-Object -ExpandProperty Name

    Add-Content -Path C:\path\to\file.txt -Value @"

$user
Security Groups 
----------------------------
"@

    foreach ($group in $groups){
        Add-Content -Path C:\path\to\file.txt -Value $group
    }
}

This is what the output looks like:

user1
Security Groups 
----------------------------
Administrators
Domain Admins

user2
Security Groups 
----------------------------
Administrators
Domain Admins
0
Community On

I think it will be something like this:

  $users = @("User1", "User2", "User3", "User4")
   $file= "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
""| Out-File $file; #Clear content of file
foreach ($user in $users){ ""| Out-File -Append $file; #Add a new line
    "$User is in Security groups:"| Out-File -Append $file; # making a Title
    "---------------------------------"| Out-File -Append $file; # making a Title
    Get-ADPrincipalGroupMembership $user | sort Name | ft -HideTableHeaders Name | Out-File -Append $file #Writing data
    }

The txt file will be replaced each time, when running script.