lib/Companies.ps1

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
}