Public/Get-SlackGroup.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
function Get-SlackGroup {
    <#
    .SYNOPSIS
        Get information about Slack groups

    .DESCRIPTION
        Get information about Slack groups

    .PARAMETER Token
        Specify a token for authorization.

        See 'Authentication' section here for more information: https://api.slack.com/web
        Test tokens are a simple way to use this

    .PARAMETER Name
        One or more group names to return. Defaults to all. Accepts wildcards.

    .PARAMETER ExcludeArchived
        Whether to exclude archived groups. Default is to include all.

    .PARAMETER Raw
        If specified, we provide raw output and do not parse any responses

    .FUNCTIONALITY
        Slack
    #>

    [cmdletbinding()]
    param (
        $Token = $Script:PSSlack.Token,
        [string[]]$Name,
        [switch]$ExcludeArchived,
        [switch]$Raw
    )
    end
    {
        Write-Verbose "$($PSBoundParameters | Out-String)"

        if($ExcludeArchived)
        {
            $body = @{ exclude_archived = 1 }
        }
        else
        {
            $body = @{ exclude_archived = 0 }
        }
        $params = @{
            Body = $body
            Token = $Token
            Method = 'groups.list'
        }
        $RawGroups = Send-SlackApi @params

        $HasWildCard = $False
        foreach($Item in $Name)
        {
            if($Item -match '\*')
            {
                $HasWildCard = $true
                break
            }
        }

        if($Name -and -not $HasWildCard)
        {       
            # torn between independent queries, or filtering groups.list
            # submit a PR if this isn't performant enough or doesn't make sense.
            $Groups = $RawGroups.groups |
                Where {$Name -Contains $_.name}
        }
        elseif ($Name -and$HasWildCard)
        {
            $AllGroups = $RawGroups.groups
            
            # allow like operator on each group requested in the param, avoid dupes
            $GroupHash = [ordered]@{}
            foreach($SlackGroup in $AllGroups)
            {
                foreach($Chan in $Name)
                {
                    if($SlackGroup.Name -like $Chan -and -not $GroupHash.Contains($SlackGroup.id))
                    {
                        $GroupHash.Add($SlackGroup.Id, $SlackGroup)
                    }
                }
            }
            $Groups = $GroupHash.Values
        }
        else # nothing specified
        {
            $Groups = $RawGroups.groups
        }

        if($Raw)
        {
            $RawGroups
        }
        else
        {
            Parse-SlackGroup -InputObject $Groups
        }
    }
}