lib/Companies.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
function Get-TMCompany {
    param(
        [Parameter(Mandatory = $false)][String]$TMSession = "Default",
        [Parameter(Mandatory = $false)][String]$Name,
        [Parameter(Mandatory = $false)][String]$Server = $global:TMSessions[$TMSession].TMServer,
        [Parameter(Mandatory = $false)]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL
    )

    ## Get Session Configuration
    $TMSessionConfig = $global:TMSessions[$TMSession]
    if (-not $TMSessionConfig) {
        Write-Host 'TMSession: [' -NoNewline
        Write-Host $TMSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-TMSession command.'
        Throw "TM Session Not Found. Use New-TMSession command before using features."
    }

    #Honor SSL Settings
    $TMCertSettings = @{SkipCertificateCheck = $TMSessionConfig.AllowInsecureSSL }
    
    # Format the uri
    $instance = $Server.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
    $uri = "https://$instance/tdstm/partyGroup/listJson"
    
    try {
        $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession @TMCertSettings
    } 
    catch {
        return $_
    }

    if ($response.StatusCode -in @(200, 204)) {
        $ResponseContent = $response.Content | ConvertFrom-Json

        # Format the response as a list of company objects
        $Results = [System.Collections.ArrayList]::new()
        foreach ($Company in $ResponseContent.rows) {
            [void]$Results.Add(
                [PSCustomObject]@{
                    id = $Company.id
                    Name = $Company.cell[0]
                    dateCreated = $Company.cell[2]
                    dateUpdated = $Company.cell[3]
                }
            )
        }
    } 
    else {
        return "Unable to collect Companies."
    }

    if ($Name) {
        $Results = $Results | Where-Object { $_.Name -eq $Name}
    }

    return $Results
}