Public/Get-MailboxGroupMembership.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
63
64
65
66
67
68
69
70
71
72
73
74
75
function Get-MailboxGroupMembership {
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        [string[]]
        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            Position = 0)]
        $Identity,
        [string[]]
        [Parameter(Position = 1)]
        $GroupIdentity
    )

    Begin {
        if ($GroupIdentity) {
            $Groups = foreach ($Group in $GroupIdentity) {
                $G = Get-DistributionGroup -Identity $Group
                if (-not $G) {
                    Write-Error -Message "Could not find group '$G'"
                    Continue
                }
                else {
                    $G
                }
            }
            [pscustomobject[]]$GroupMembers = foreach ($Group in $Groups) {
                Write-Verbose -Message "Getting members for group '$($Group.Name)'"
                $Members = Get-DistributionGroupMember -Identity $Group.Name
                [pscustomobject]@{
                    GroupName = $Group.Name
                    Members   = $Members
                }
            }
        }
        else {
            Write-Verbose -Message "Getting all distribution groups"
            $Groups = Get-DistributionGroup
            Write-Verbose -Message "Getting members of all groups"
            [pscustomobject[]]$GroupMembers = foreach ($Group in $Groups) {
                $Members = Get-DistributionGroupMember -Identity $Group.Name
                [pscustomobject]@{
                    GroupName = $Group.Name
                    Members   = $Members
                }
            }
        }
    }
    Process {
        foreach ($User in $Identity) {
            $Mailbox = Get-Mailbox -Identity $User -ErrorAction SilentlyContinue
            if (-not $Mailbox) {
                Write-Error -Message "Could not find mailbox for user '$User'"
                Continue
            }
            Write-Verbose -Message "Found mailbox for '$User'"
            $UserGroups = foreach ($Group in $Groups) {
                foreach ($Member in $GroupMembers.Where( { $_.GroupName -eq $Group.Name }).Members | Where-Object -Property Alias -eq $Mailbox.Alias) {
                    $Group
                    Write-Verbose -Message "Found '$user' in '$($Group.Name)'"
                }
            }
            $OutputObject = [pscustomobject]@{
                UserDisplayName        = $Mailbox.DisplayName
                Mailbox                = $Mailbox
                Groups                 = $UserGroups
            }
            $OutputObject
        }
    }
    End {
    }
}