简体   繁体   中英

Powershell list all members of local machine groups

Current script below works but it displays members in one line delimited by |. I would like to have one row per member table format.

$script = {
    $groups = Get-CimInstance win32_group -filter "domain='$($env:computername)'"
    foreach ($group in $groups) {
    Get-CimInstance win32_groupuser -filter "GroupComponent=""Win32_Group.Domain='$($env:computername)',Name='$($group.Name)'""" 
    } 
}
$output = Invoke-Command -ComputerName $servers.Name -ScriptBlock $script -ErrorAction SilentlyContinue
$output | Group PSComputerName,GroupComponent | Foreach-Object {
    [pscustomobject]@{
    Server = $_.Group[0].PSComputerName
    Group = $_.Group[0].GroupComponent.Name
    Members = $_.Group.PartComponent.Name -join '|'
    }
} | Export-Csv "C:\Users\someuser\Documents\PowerShell\AccessOutput5.csv" -NoType 

Results look like this

"DummyServer","Administrators","Wintel4OPS|LocalIs|Domain Admins|Win_EP_Accounts|Win_EP_Admin_USA|Win_EP_Eng|Win_EP_Delivery_Svc"
"DummyServer","Backup Operators","MSSQLSERVER"
"DummyServer","Event Log Readers","NETWORK SERVICE"
"DummyServer","Guests","UHT-Guest"
"DummyServer","IIS_IUSRS","IUSR"
"DummyServer","Performance Log Users","jdoe"
"DummyServer","Performance Monitor Users","MSSQLSERVER|SQLSERVERAGENT"
"DummyServer","Users","INTERACTIVE|Authenticated Users|Domain Users|CLIUSR"
"DummyServer","Guardium Services","LOCAL SERVICE"
"DummyServer","SQLServer2005SQLBrowserUser$DummyServer","SQLBrowser"
"DummyServer","SQLServerHADRUser$MSSQLSERVER","MSSQLSERVER"

This is hard to read when you have 200+ servers. How can I change the current script so there is one line per member server name and group would be duplicated and that is fine

Desired output

"DummyServer","Administrators","Wintel4OPS" 
"DummyServer","Administrators","LocalIs"
"DummyServer","Administrators","Domain"

Instead of joining each member with the | character, you can run a foreach loop for each of the objects in $_.Group.PartComponent.Name

$output | Group PSComputerName,GroupComponent | Foreach-Object {
    foreach ($member in $_.Group.PartComponent.Name)
    {
        [pscustomobject]@{
            Server = $_.Group[0].PSComputerName
            Group = $_.Group[0].GroupComponent.Name
            Members = $member
        }
    }
} | Export-Csv "C:\Users\someuser\Documents\PowerShell\AccessOutput5.csv" -NoType 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM