Home > Software design >  Output membership of certain Window local groups
Output membership of certain Window local groups

Time:05-24

Working on a simple script to loop through a bunch of machines through a 3rd party system and output the machine, group, and the user to a PS object.

Have the script outputting the correct groups/users. However when a group has more than one user, then it renders it on the same line, instead of a new line. Just looking for insight on how to properly format the output so each result is on it's own line.

  $params = $args
$Target = $args[0]
$PrivUser = "$($params[1])\$($params[2])"
$PrivPwd = ConvertTo-SecureString -String $params[3] -AsPlainText -Force
$cred = [pscredential]::new($PrivUser,$PrivPwd)
$Groups =  @('Administrators','Power Users')
$results = @()
try {
    Invoke-Command -ComputerName $Target -Credential $cred -HideComputerName -ScriptBlock {
        $lgs =  Get-LocalGroup -Name $Groups
        Foreach ($lg in $lgs) {
            $ms = Get-LocalGroupMember -Name $lg
            #write-host $ms.Name
            $output = New-Object PSObject -Property @{
                Machine = $env:COMPUTERNAME
                Group = "$lg"
                Username=$ms
            }
            $results  = $output
        }
        return $results 
        
    }
 } catch {
    throw "Unable to connect to target: $($args[0]) `n$_"
}

results:

Username                                                                   Group          Machine   
--------                                                                   -----          -------   
{BLT\clepley, BLT\clepley_admin, BLT\Domain Admins, BLT\svr.blt.div.ss...} Administrators BLT-SS-WEB
BLT\clepley_admin                                                          Power Users    BLT-SS-WEB

CodePudding user response:

Seems like you're missing an inner loop in case the membership is greater than one:

Invoke-Command -ComputerName $Target -Credential $cred -HideComputerName -ScriptBlock {
    foreach($group in $using:Groups) {
        foreach($member in Get-LocalGroupMember -Name $group) {
            [pscustomobject]@{
                Machine     = $env:COMPUTERNAME
                Group       = $group
                Member      = $member.Name
                ObjectClass = $member.ObjectClass
            }
        }
    }
}

However note, there is no error handling here, hence, this assumes the Power Users Group exists in the remote computers.

It's also worth noting the use of the $using: scope modifier, which allows you to access the local variable $Groups in the remote scope.

  • Related