Script to display information in CSV

Hi, I am just beginning to learn Powershell and working on a local script that I will then alter to work in AD (working on it at home and don’t have AD at home yet to work with). The plan in AD is to create a similar file but pulling users and the groups they are member of via Get-ADPrincipalGroupMembership. The script works, but I feel like it is too convoluted and there is an easier way to get the information I want. I think the issue I was running into the most trouble with was having the group name and user accounts in the end array. It just seems like there is a simpler solution that I can’t see.

Thanks

 

$groups = get-localgroup
$array = @()
foreach ($group in $groups) {
  $users = get-localgroupmember $group
  $result = "" | select Group,Users
  $result.group = $group.name
  $userarray = @()
  foreach ($user in $users) {
    $userarray += $user.name
  }
  $result.Users = ($userarray -join ',')
  $array += $result
}
$array | export-csv C:\Groups.csv

i might be absent some short hand syntax or other, but i can’t see how to make that more readable, it is rather elegant in its current form

I don’t have an AD to test at the moment as well but usually when you want to combine the results of two or more “queries” to one result a PSCustomObject is likely more readably and easier to maintain … something like this:

$groups = Get-LocalGroup
$array = foreach ($group in $groups) {
$member = Get-LocalGroupMember -Group $group
[PSCustomObject]@{
Group = $group
Member = $member.name -join ‘,’
}
}
$array | export-csv C:\Groups.csv

And - according to the amount of groups and users - it should be a little faster than your aproach. :wink:

You can use the free TechNet virtual AD and other labs to practice stuff like this.

Self-paced Labs Acquire the cloud skills you need, at your own pace. Enjoy hands-on learning on your schedule with our free, self-paced labs, and keep your cloud knowledge fresh.

https://www.microsoft.com/handsonlabs/selfpacedlabs

As for this…

The plan in AD is to create a similar file but pulling users and the groups they are member of via Get-ADPrincipalGroupMembership.
... There are lots of examples on line that do what you are after or can easily be tweaked.

Also, Vs using …

Get-ADPrincipalGroupMembership

… for your use case. You could also just do this …

# Create group membership file
ForEach ($GroupName in (Get-ADGroup -Filter '*').Name)
{
    Get-ADGroupMember -Identity $GroupName | 
    Where-Object -Property objectClass -eq 'User' | 
    Select-Object -Property @{Name = 'GroupName';Expression = {$GroupName}},SamAccountName | 
    Export-csv -Path 'D:\Temp\GroupMemberShips.csv' -NoTypeInformation -Append
} 

# Read the membership file
Import-Csv -Path 'D:\Temp\GroupMemberShips.csv' |  
Format-Table -AutoSize

<#
# Results

GroupName                              SamAccountName      
---------                              --------------      
...         
Administrators                         Administrator       
Users                                  testuser1           
...         
Guests                                 Guest               
...          
Schema Admins                          Administrator       
...          
Enterprise Admins                      Administrator       
Domain Admins                          Administrator       
...           
Domain Users                           Administrator       
...         
Domain Users                           krbtgt              
...         
Domain Users                           testuser1           
Domain Users                           testuser2           
Domain Guests                          Guest               
Group Policy Creator Owners            Administrator       
...        
Organization Management                Administrator       
...         
Recipient Management                   Administrator       
...           
ADSyncAdmins                           Administrator       
...       
#>


# Read the group membership file grouped to see member count per group
Import-Csv -Path 'C:\Temp\GroupMemberShips.csv' | 
Group-Object -Property GroupName | 
Select-Object -Property Count, Name, 
@{Name = 'Members';Expression = {$PSItem.Group.SamAccountName}} | 
Format-Table -AutoSize

<#
# Results

Count Name                                   Members                                             
----- ----                                   -------                                             
    2 Administrators                         {Administrator...}
    4 Users                                  {testuser1, ...}  
    1 Guests                                 Guest  
...

You say …

I am just beginning to learn Powershell

Use tools that will write the code for you that you can later tweak. Specifically for ADDS, this is a built in thing on Windows Server. It’s called the PowerShell History Viewer.

Active Directory Administrative Center: Getting Started 'https://technet.microsoft.com/en-us/library/dd560651(v=ws.10).aspx'

Active Directory Administrative Center
Introduction to Active Directory Administrative Center Enhancements (Level 100) | Microsoft Learn

Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2
Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2 | Microsoft Learn

Leverage all the samples on the MS powershellgallery and TechNet script center.

… There are a tons of no cost / free resources to use. Even on this very site, Just click the ‘Free Resources’ link in the left navigation pane. As well as leveraging these discussion / references of folks trying to learn as well.

https://www.reddit.com/r/PowerShell/comments/aw4l4z/new_to_ps_coding_background https://www.reddit.com/r/PowerShell/comments/aw8cvk/course_to_increase_knowledge_of_windows/ehl4ixm/?context=3 https://www.reddit.com/r/PowerShell/comments/ausa1n/beginner_help/ehawij5/?context=3 https://www.reddit.com/r/PowerShell/comments/ar6cvt/powershell_in_depth_second_edition/egmlpom/?context=3 https://ww.reddit.com/r/PowerShell/comments/afqmmw/i_want_to_help_my_husband_advance_his_powershell/ee3k6p6/?context=3 ​ And this... https://docs.microsoft.com/en-us/powershell https://blogs.msmvps.com/richardsiddaway/2019/02/21/the-source-of-powershell-cmdlets

Thanks for the help that was exactly what I was looking for, and even better a new tool to learn about :slight_smile:

I am learning both for my own knowledge and for implementing at work, so trying to get the stuff that will be in a production environment a bit cleaner while I am still learning.

Thank you for the resources, I will definitely look into them. The difference with the AD version was I was wanting a list of users with the groups that they were a member of, instead of groups with users. That was why I was going to determine the users then use Get-ADPrincipalGroupMembership to get the groups they were members of. I just couldn’t find an easy way to display that locally so went with localgroups -> localusers for testing a way to get variables from different objects. But thank you for taking the time to go through that and all of the other resources. They will help a lot.

OK, as for …

The difference with the AD version was I was wanting a list of users with the groups that they were a member of, instead of groups with users. That was why I was going to determine the users then use Get-ADPrincipalGroupMembership to get the groups they were members of.

… that too can be as simple as …

ForEach ($TargetUser in (Get-ADUser -Filter *))
{
    "`n Showing group membership for $($TargetUser.SamAccountName)"
    Get-ADPrincipalGroupMembership -Identity $TargetUser.SamAccountName | Select Name
}


<#
#Results

<#
#Results

Showing group membership for Administrator
Name        
----        
Domain Users
Administrators
Schema Admins 
Enterprise Admins
Domain Admins
Group Policy Creator Owners
Organization Management    
Recipient Management       
ADSyncAdmins
ADRMSSuperUsers  

Showing group membership for Guest
Domain Guests 
Guests      

...
#>