Public/Get-iPilotDepartment.ps1

Function Get-iPilotDepartment {
    <#
        .Synopsis
        Displays iPilot user(s)

        .Description
        Returns iPilot Department in iPilot domain with optional filters.

        .Parameter DepartmentName
        Filter results by user's First Name.

        .Parameter ApiVersion
        Version of the NuWave iPilot to use. Defaults to v1.

        .Parameter iPilotDomain
        iPilot Domain Name.

        .Parameter NumberOfRecords
        Number of records returned by API (limit 100)

        .Example
        # Get avilable numbers with the status set to Configured using API Version v1 in the contoso.com iPilot domain
        Get-iPilotDepartment -NumberOfRecords 10 -iPilotDomain contoso.com

        .Example
        # Get department named "Sales and Marketing" in the contoso.com iPilot domain with Verbose output
        Get-iPilotDepartment -DepartmentName "Sales and Marketing" -iPilotDomain contoso.com -Verbose
    #>

    Param (
        [Parameter(
            Mandatory = $false,
            ValueFromPipeline = $true,
            HelpMessage = 'Allowed characters: Alphanumeric, spaces, and hyphens')]
            [ValidatePattern('^[a-zA-Z0-9 ]+$')]
            [System.String] $DepartmentName,
        [System.String]
            $ApiUrl = $global:IP_ApiUrl, 
        [System.String]
            $ApiKey = $global:IP_ApiKey, 
        [System.String]
            $ApiVersion = "v1",
        [System.String]
            $iPilotDomain = $global:IP_iPilotDomain,
        [System.Int16]
            $NumberOfRecords = [System.Int16]::MaxValue,
        [System.Management.Automation.PSCredential]
            $Credential
     )

    Begin {

        # Set iPilot Domain
        if (!$global:IP_iPilotDomain -and !$iPilotDomain) {
            throw "Run Get-iPilotTeamsDomain or provide domain using -iPilotDomain"
        } elseif (!$iPilotDomain) {
            $iPilotDomain = $global:IP_iPilotDomain
            Write-Verbose "iPilot Domain: $iPilotDomain"
        } # else use passed in iPilotDomain
    }

    Process {
        # Verbose Switch
        if($PSBoundParameters.containskey("Verbose")) {
            $PreviousVerbosePreference = $VerbosePreference
            $VerbosePreference = "continue"
        }

        # Debug Switch
        if($PSBoundParameters.containskey("Debug")) {
            $PreviousDebugPreference = $DebugPreference
            $DebugPreference = "continue"
        }

        # Get/re-use OAuth Token
        $InitializeiPilotSessionSplat = @{
            ApiUrl = $ApiUrl
            ApiVersion = $ApiVersion
            ApiKey = $ApiKey
            Credential = $Credential
        }
        if ($global:IP_Instance) {
            $InitializeiPilotSessionSplat += @{
                Instance = $global:IP_Instance
            }
        }
        if ($VerbosePreference -eq "Continue") {
            $InitializeiPilotSessionSplat += @{
                Verbose = $true
            }
        }
        if ($DebugPreference -eq "Continue") {
            $InitializeiPilotSessionSplat += @{
                Debug = $true
            }
        }
        Initialize-iPilotSession @InitializeiPilotSessionSplat

        # Build iPilot API Request
        $GetiPilotDepartmentRequestUri = "$ApiUrl/$ApiVersion/msteams/$iPilotDomain/departments?limit=$NumberOfRecords&page=1"
        if ($Instance) {
            $GetiPilotDepartmentRequestUri += "&instance=$Instance"
        }
        Write-Verbose "Request Uri: $GetiPilotDepartmentRequestUri"

        # Splat Invoke-RestMethod parameters
        Write-Verbose "Request Method: Get"
        $GetiPilotDepartmentInvokeParams = @{
            Uri = $GetiPilotDepartmentRequestUri
            Method = "Get"
            ContentType = "application/json"
            Headers = @{
                "X-Access-Token" = $iPilotOAuthToken.access_token
                "x-api-key"      = $iPilotApiKey
            }
        }

        Write-Verbose "GetiPilotDepartmentInvokeParams:`n$($GetiPilotDepartmentInvokeParams | Format-Table | Out-String)" -Verbose

        # Execute the REST API
        Try {
            $GetiPilotDepartmentResponse = Invoke-RestMethod @GetiPilotDepartmentInvokeParams -ErrorAction Stop
            Write-Debug "GetiPilotDepartmentResponse:`n$GetiPilotDepartmentResponse"
        } Catch {
            Write-Error "Failed to retreive iPilot Department(s)`nStatus: $($GetiPilotDepartmentResponse.status)`nURL: $($GetiPilotDepartmentRequestUri). Error: $($_)"
            break
        }

        # Convert response object to array of objects
        $Departments = @()
        ($GetiPilotDepartmentResponse.departments | Out-String) -split "`r`n" | Where-Object {$_} | ForEach-Object {
            $Department = $_.Split(":").TrimStart()
            $Departments += [pscustomobject]@{'DepartmentId'=$Department[0];'DepartmentName'=$Department[1]}
        }
        Write-Debug "Departments:`n$Departments"

        # If DepartmentName specified, return ID
        if ($DepartmentName) {
            $Departments = $Departments | Where-Object {$_.DepartmentName -eq $DepartmentName}
        }

        # Return Department Array
        if ($Departments) {
            return $Departments
        } else {
            Write-Error "No Department found."
        }

        # Verbose Switch
        if($PSBoundParameters.containskey("Verbose")) {
            $VerbosePreference = $PreviousVerbosePreference
        }

        # Debug Switch
        if($PSBoundParameters.containskey("Debug")) {
            $DebugPreference = $PreviousDebugPreference
        }
    }
}