Get-LocalGroupMembership.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<#
.Synopsis
   Gets a list of members in a particular local group.
.DESCRIPTION
   Gets a list of members in a particular local group.
 
.NOTES
   Created by: Jason Wasser @wasserja
   Modified: 4/3/2015 03:24:26 PM
.EXAMPLE
   Get-LocalGroupMembership | Select-Object -ExpandProperty GroupMembers
   Lists the members of the Administrators group of the local computer.
.EXAMPLE
   Get-LocalGroupMembership -ComputerName SERVER01
   Lists the members of the Administrators group on SERVER01.
.EXAMPLE
   Get-LocalGroupMembership -ComputerName SERVER01,SERVER02 -Groups "Remote Desktop Users"
   Lists the members of the Remote Desktop Users group on SERVER01 and SERVER02.
#>

function Get-LocalGroupMembership
{
    [CmdletBinding()]
    #[OutputType([int])]
    Param
    (
        # ComputerName
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string[]]$ComputerName=$env:COMPUTERNAME,

        # Group Name
        [Parameter(Mandatory=$false,
                    ValueFromPipelineByPropertyName=$true,
                    Position=1)]
        [string[]]$Groups="Administrators"
    )

    Begin
    {
    }
    Process
    {
        foreach ($Computer in $ComputerName) {
            #Write-Verbose
            foreach ($Group in $Groups) {
                $LocalGroup = [ADSI]"WinNT://$Computer/$Group"
                $Members = @($LocalGroup.Invoke("Members")) | foreach { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }
                $propHash = [ordered]@{
                    ComputerName = $ComputerName
                    GroupName = $Group
                    GroupMembers = $Members
                    }
                $GroupMembers = New-Object -type PSObject -Property $propHash
                $GroupMembers
                }
            }
    }
    End
    {
    }
}