Public/Tasks.ps1

function Get-TMTask {
    <#
    .SYNOPSIS
    Gets one or more Tasks from TransitionManager using optional filters
 
    .DESCRIPTION
    This function gets one or more Tasks from TransitionManager by Id, Number,
    Task Spec Id, Status, Asset Name, Asset Type, Action Name, or Category.
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER EventName
    One or more Event Names to filter by
 
    .PARAMETER Id
    One or more Task Ids to filter by
 
    .PARAMETER TaskNumber
    One or more Task numbers to filter by
 
    .PARAMETER TaskSpecId
    One or more Task spec Ids to filter by
 
    .PARAMETER Status
    One or more Statuses to filter by
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER AssetName
    One or more Asset names to filter by
 
    .PARAMETER AssetType
    One or more Asset types to filter by
 
    .PARAMETER AssetClass
    One or more Asset classes to filter by
    Valid values are: Device, Application, Storage, Database
 
    .PARAMETER ActionName
    One or more Action names to filter by
 
    .PARAMETER Category
    One or more Task categories to filter by
 
    .PARAMETER Title
    One or more Task Titles/Comments to filter by. Accepts wildcard characters
 
    .PARAMETER Team
    One or more Team names to filter by
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .PARAMETER TMQL
    Boolean indicating that TMQL queries should be used in favor of web service and REST API endpoints
 
    .PARAMETER IncludeTaskDependencyDetails
    Switch indicating that, when using TMQL, the secondary query for Task Dependencies should be executed to provide
    more details about the Task's Predecessors and Successors
 
    .EXAMPLE
    Get-TMTask -TMSession $ProfileName -Status 'Completed', 'Ready' -Event 'TEST Event'
 
    .EXAMPLE
    Get-TMTask -TaskNumbers 12345, 165876, 30559
 
    .EXAMPLE
    # Get all Tasks from the 'TEST Event' Event that have a 'Server' type associated Asset and the 'HCX - Switchover' Action
    Get-TMTask -AssetType 'Server' -ActionName 'HCX - Switchover' -Event 'TEST Event'
 
    .OUTPUTS
    One or more TMTask objects representing the results of the filtered search
    #>

    [OutputType([TMTask[]])]
    [CmdletBinding(DefaultParameterSetName = 'ByTaskProperties')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $false, Position = 1)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId = $TMSessions[$TMSession].UserContext.Project.Id,

        [Parameter(Mandatory = $false)]
        [Alias('Event', 'TMEvent')]
        [Object[]]$EventName,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ById')]
        [Alias('TaskId')]
        [Int[]]$Id,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('Number')]
        [Int[]]$TaskNumber,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('TaskSpec')]
        [Int[]]$TaskSpecId,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [Alias('TaskStatus')]
        [String[]]$Status,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('Asset')]
        [String[]]$AssetName,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [String[]]$AssetType,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [ValidateSet('Application', 'Device', 'Database', 'Storage')]
        [String[]]$AssetClass,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('TaskAction')]
        [String[]]$ActionName,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('TaskCategory')]
        [String[]]$Category,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('Comment', 'TaskTitle', 'TaskComment')]
        [String[]]$Title,

        [Parameter(Mandatory = $false, ParameterSetName = 'ByTaskProperties')]
        [Alias('Role')]
        [String[]]$Team,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Bool]$TMQL = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$IncludeTaskDependencyDetails
    )


    begin {

        function Get-FilteredTasksAPI([Hashtable]$Filters) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()

            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri                  = "https://$($TMSession.TMServer)/tdstm/api/task?rows=1000&page=1"
                Method               = 'GET'
                WebSession           = $TMSession.TMRestSession
                StatusCodeVariable   = 'StatusCode'
                SkipHttpErrorCheck   = $true
                SkipCertificateCheck = $TMSession.AllowInsecureSSL
                Body                 = ($Filters | ConvertTo-Json -Depth 5 -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 5)
            Write-Verbose "Invoking REST method"
            $Response = Invoke-RestMethod @RestSplat

            Write-Debug "Status Code: $StatusCode"
            if ($StatusCode -in 200, 204) {
                Write-Verbose "Formatting response content"

                ## Assign the Rows variable based on what TM provides back
                if ($Response.PSObject.Properties.Name -contains 'rows') {
                    $Rows = $Response.rows
                } elseif ($Response.PSObject.Properties.Name -contains 'records') {
                    $Rows = $Response.records
                } elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                    $Rows = $Response.tasks
                }

                foreach ($Row in $Rows) {
                    try {
                        $TaskList.Add([TMTask]::new($Row))
                    } catch {
                        Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                    }
                }

                if ($Response.total -gt 1) {
                    for ($i = 2; $i -le $Response.total; $i++) {
                        Write-Verbose "Forming web request parameters"
                        $RestSplat.Uri = "https://$($TMSession.TMServer)/tdstm/api/task?rows=1000&page=$i"
                        Write-Debug "Web Request Parameters:"
                        Write-Debug ($RestSplat | ConvertTo-Json -Depth 5)
                        Write-Verbose "Invoking REST method"
                        $Response = Invoke-RestMethod @RestSplat

                        Write-Debug "Status Code: $StatusCode"
                        if ($StatusCode -in 200, 204) {
                            Write-Verbose "Formatting response content"

                            ## Assign the Rows variable based on what TM provides back
                            if ($Response.PSObject.Properties.Name -contains 'rows') {
                                $Rows = $Response.rows
                            } elseif ($Response.PSObject.Properties.Name -contains 'records') {
                                $Rows = $Response.records
                            } elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                                $Rows = $Response.tasks
                            }

                            foreach ($Row in $Rows) {
                                try {
                                    $TaskList.Add([TMTask]::new($Row))
                                } catch {
                                    Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                                }
                            }
                        } else {
                            Write-Error "The response status code $($StatusCode) does not indicate success: $([System.Net.HttpStatusCode] $StatusCode)"
                        }
                    }
                }
            } else {
                Write-Error "The response status code $($StatusCode) does not indicate success: $([System.Net.HttpStatusCode] $StatusCode)"
            }

            , $TaskList
        }


        function Get-FilteredTasksWS([Hashtable]$Filters) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()

            Write-Verbose "Formatting filters"
            $FilterStrings = @()
            foreach ($Key in $Filters.Keys) {
                $FilterStrings += "$($Key)=$([System.Web.HttpUtility]::UrlEncode($Filters.$Key))"
            }
            Write-Debug "FilterStrings: $($FilterStrings -join "`n")"

            Write-Verbose "Using Web Services endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri                  = "https://$($TMSession.TMServer)/tdstm/ws/task?" + ($FilterStrings -join '&')
                Method               = "GET"
                WebSession           = $TMSession.TMWebSession
                SkipHttpErrorCheck   = $true
                SkipCertificateCheck = $TMSession.AllowInsecureSSL

            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 5)
            Write-Verbose "Invoking web request"
            $Response = Invoke-WebRequest @WebRequestSplat

            Write-Debug "Status Code: $($Response.StatusCode)"
            if ($Response.StatusCode -in 200, 204) {
                Write-Verbose "Formatting response content"
                $ResponseContent = $Response.Content | ConvertFrom-Json -Depth 5
                if ($ResponseContent.status -match 'error') {
                    Write-Error "Could not get tasks: $($ResponseContent.errors)"
                } else {
                    foreach ($Row in $ResponseContent.data) {
                        try {
                            $TaskList.Add([TMTask]::new($Row))
                        } catch {
                            Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                        }
                    }
                }
            } else {
                Write-Error "The response status code $($Response.StatusCode) does not indicate success"
            }

            , $TaskList
        }


        function Get-FilteredTasksTMQL([String[]]$Filters) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()

            # Use a StringBuilder to build the query for TM
            Write-Verbose "Forming TMQL query"
            $Query = [System.Text.StringBuilder]::new()
            [void]$Query.AppendLine("find Task by \")
            [void]$Query.AppendLine($Filters[0] + " \")
            for ($i = 1; $i -lt $Filters.Count; $i++) {
                [void]$Query.AppendLine("and " + $Filters[$i] + " \")
            }
            [void]$Query.AppendLine([TMTask]::TMQLFetchString)

            # Query TM for the Tasks and convert them to TMTask objects
            Write-Verbose "Invoking the TMQL statement"
            Write-Debug "TMQL Query:`n`n$($Query.ToString())"
            (Invoke-TMQLStatement -TMSession $TMSession -Statement $Query.ToString()) | ForEach-Object {
                $TaskList.Add([TMTask]::new($_))
            }

            # Replace the Task Dependencies
            if ($IncludeTaskDependencyDetails) {
                foreach ($Task in $TaskList) {
                    $Task.Successors = $TaskDependencies | Where-Object { $_.TaskId -in $Task.Successors.TaskId }
                    $Task.Predecessors = $TaskDependencies | Where-Object { $_.TaskId -eq $Task.Id }
                }
            }

            , $TaskList
        }


        function Get-FilteredTaskDependenciesTMQL([String[]]$Filters) {
            $TaskDependencyList = [System.Collections.Generic.List[TMTaskDependency]]::new()

            # Use a StringBuilder to build the query for TM
            Write-Verbose "Forming TMQL query"
            $Query = [System.Text.StringBuilder]::new()
            [void]$Query.AppendLine("find TaskDependency by \")
            [void]$Query.AppendLine($Filters[0] + " \")
            for ($i = 1; $i -lt $Filters.Count; $i++) {
                [void]$Query.AppendLine("and " + $Filters[$i] + " \")
            }
            [void]$Query.AppendLine([TMTaskDependency]::TMQLFetchString)

            # Query TM for the Tasks and convert them to TMTask objects
            Write-Verbose "Invoking the TMQL statement"
            Write-Debug "TMQL Query:`n`n$($Query.ToString())"
            (Invoke-TMQLStatement -TMSession $TMSession -Statement $Query.ToString()) | ForEach-Object {
                $TaskDependencyList.Add(
                    [TMTaskDependency]::new(
                        $_.id,
                        $_.'assetComment.id',
                        $_.'assetComment.taskNumber',
                        $_.'assetComment.comment'
                    )
                )
            }

            , $TaskDependencyList
        }


        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)


        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSession.UserContext.Project.id

        $Tasks = [System.Collections.Generic.List[TMTask]]::new()

        # Create a list for post-request filters to be applied to the returned Tasks
        $TaskFilters = [System.Collections.Generic.List[ScriptBlock]]::new()

        # Gather a list of just the event names. Added for backwards compatibility
        if ($EventName -and ($EventName[0] -is [TMEvent])) {
            [String[]]$EventName = $EventName.Name
        }

        # Determine which endpoint to hit based on the TM version and REST session and set up the base filters
        # REST = TASK REST API
        # WS50 = Web Services using ATE
        # WS47 = Web Services without ATE
        # TMQL - TMQL REST API
        Write-Verbose "Determining TM endpoint to use and setting up filters"
        if ($TMQL) {
            $Endpoint = 'TMQL'
            $TaskDependencies = [System.Collections.Generic.List[TMTaskDependency]]::new()
            $RequestFilters = @( "'project.id' eq $ProjectId" )

            if ($PSCmdlet.ParameterSetName -eq 'ById' -and $IncludeTaskDependencyDetails) {
                $TaskDependencies.AddRange((Get-FilteredTaskDependenciesTMQL -Filters @("'assetComment.id' inList([$($Id -join ', ')])")))
                $TaskDependencies.AddRange((Get-FilteredTaskDependenciesTMQL -Filters @("'predecessor.id' inList([$($Id -join ', ')])")))
            } else {
                if ($EventName) {
                    if ($EventName.Count -eq 1) {
                        $RequestFilters += "'moveEvent.name' eq '$($EventName[0])'"
                        $TaskDependencyRequestFilters += "'assetComment.moveEvent.name' eq '$($EventName[0])'"
                    } else {
                        $RequestFilters += "'moveEvent.name' ate '$($EventName -join '|')'"
                        $TaskDependencyRequestFilters += "'assetComment.moveEvent.name' ate '$($EventName -join '|')'"
                        $TaskFilters.Add([ScriptBlock]::Create("`$_.Event.Name -in '$($EventName -join "', '")'"))
                    }
                } else {
                    $TaskDependencyRequestFilters = @( "'id' ne 0" )
                }

                if ($IncludeTaskDependencyDetails) {
                    $TaskDependencies.AddRange((Get-FilteredTaskDependenciesTMQL -Filters $TaskDependencyRequestFilters))
                }
            }

        } elseif ($Api) {
            $Endpoint = 'REST'
            $RequestFilters = @{
                project = $ProjectId
            }

            if ($EventName) {
                if ($TMSession.TMVersion -ge '6.0.1.2') {
                    $TaskFilters.Add([ScriptBlock]::Create("`$_.Event.Name -in '$($EventName -join "', '")'"))
                } else {
                    if ($EventName.Count -gt 1) {
                        Write-Warning "Filtering with multiple Event Names is only supported in TMQL. Only the first Event Name passed '$($EventName[0])' will be used"
                    }
                    $RequestFilters.event = @{name = $EventName[0] }
                }
            }

            ## Wrap the request with the right syntax for Newer API version requirements
        } else {
            $Endpoint = $TMSession.TMVersion -like '4.*' ? 'WS47' : 'WS50'
            $RequestFilters = @{
                projectId = $ProjectId
            }

            if ($EventName) {
                try {
                    $EventId = (Invoke-TMQLStatement -Statement "find Event by 'name' eq '$($EventName[0])' fetch 'id'").id
                    $RequestFilters.moveEvent = $EventId
                    if ($EventName.Count -gt 1) {
                        Write-Warning "Filtering with multiple Event Names is only supported in TMQL. Only the first Event Name passed '$($EventName[0])' will be used"
                    }
                } catch {
                    $TaskFilters.Add([ScriptBlock]::Create("{$_.Event.Name -in '$($EventName -join "', '")'}"))
                }
            }
        }
        Write-Debug "Endpoint: $Endpoint"
        Write-Debug "Initial Request Filters:`n$($RequestFilters | ConvertTo-Json)"
    }

    process {

        Write-Debug "Parameter Set: $($PSCmdlet.ParameterSetName)"
        if ($PSCmdlet.ParameterSetName -eq 'ById') {
            Write-Verbose "Requesting Tasks by Id"
            switch ($Endpoint) {
                'TMQL' {
                    Write-Verbose "Using TMQL endpoint"
                    $RequestFilters += "'id' inList([$($Id -join ', ')])"
                    $Tasks.AddRange((Get-FilteredTasksTMQL -Filters $RequestFilters))
                }
                'REST' {
                    Write-Verbose "Using REST API endpoint"
                    $Id | ForEach-Object {
                        Write-Verbose "Forming web request parameters"
                        $RestSplat = @{
                            Uri                  = "https://$($TMSession.TMServer)/tdstm/api/task/$($_)?project=$($ProjectId)"
                            Method               = 'GET'
                            WebSession           = $TMSession.TMRestSession
                            StatusCodeVariable   = 'StatusCode'
                            SkipHttpErrorCheck   = $true
                            SkipCertificateCheck = $TMSession.AllowInsecureSSL
                        }
                        Write-Debug "Web Request Parameters:"
                        Write-Debug ($RestSplat | ConvertTo-Json -Depth 5)
                        Write-Verbose "Invoking REST method"
                        $Response = Invoke-RestMethod @RestSplat

                        Write-Debug "Status Code: $StatusCode"
                        if ($StatusCode -in 200, 204) {
                            Write-Verbose "Formatting response content"
                            $Tasks.Add([TMTask]::new($Response))
                        } else {
                            Write-Error "The response status code $($StatusCode) does not indicate success: $([System.Net.HttpStatusCode] $StatusCode)"
                        }
                    }
                }
                { $_ -in 'WS50', 'WS47' } {
                    Write-Verbose "Using Web Services endpoint"

                    $Id | ForEach-Object {
                        Write-Verbose "Forming web request parameters"
                        $WebRequestSplat = @{
                            Uri                  = "https://$($TMSession.TMServer)/tdstm/assetEntity/showComment?id=$($_)"
                            Method               = 'GET'
                            WebSession           = $TMSession.TMWebSession
                            SkipHttpErrorCheck   = $true
                            SkipCertificateCheck = $TMSession.AllowInsecureSSL
                        }
                        Write-Debug "Web Request Parameters:"
                        Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 5)
                        Write-Verbose "Invoking web request"
                        $Response = Invoke-WebRequest @WebRequestSplat

                        Write-Debug "Status Code: $($Response.StatusCode)"
                        if ($Response.StatusCode -in 200, 204) {
                            Write-Verbose "Formatting response content"
                            $ResponseContent = $Response.Content | ConvertFrom-Json
                            $Tasks.Add([TMTask]::new($ResponseContent.assetComment))
                        } else {
                            Write-Error "The response status code $($Response.StatusCode) does not indicate success: $([System.Net.HttpStatusCode] $Response.StatusCode)"
                        }
                    }
                }
            }
        } else {
            Write-Verbose "Requesting Tasks by filter properties"

            # Add parameter values to the request and task filters
            Write-Verbose "Formatting request and post-request filters"
            if ($TaskNumber) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'taskNumber' ate '$($TaskNumber -join '|')'" }
                    'WS50' { $RequestFilters.taskNumber = $TaskNumber -join '|' }
                    { $_ -in 'REST', 'WS47' } {
                        if ($TaskNumber.Count -eq 1) {
                            $RequestFilters.taskNumber = $TaskNumber[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.TaskNumber -in $($TaskNumber -join ', ')"))
                        }
                    }
                }
            }

            if ($TaskSpecId) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'taskSpec' ate '$($TaskSpecId -join '|')'" }
                    'WS50' { $RequestFilters.taskSpec = $TaskSpecId -join '|' }
                    'REST' { Write-Error "Filtering by Task Spec ID cannot be performed against the REST API endpoint" }
                    'WS47' { $RequestFilters.taskSpec = $TaskSpecId[0] }
                }
            }

            if ($Status) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'status' ate '$($Status -join '|')'" }
                    'WS50' { $RequestFilters.status = $Status -join '|' }
                    { $_ -in 'REST', 'WS47' } {
                        if ($Status.Count -eq 1) {
                            $RequestFilters.status = $Status[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Status -in '$($Status -join "', '")'"))
                        }
                    }
                }
            }

            if ($AssetName) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'assetEntity.Name' ate '$($AssetName -join '|')'" }
                    'WS50' { $RequestFilters.assetName = $AssetName -join '|' }
                    'REST' {
                        if ($AssetName.Count -eq 1) {
                            $RequestFilters.asset = @{name = $AssetName[0] }
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Asset.Name -in '$($AssetName -join "', '")'"))
                        }
                    }
                    'WS47' {
                        if ($AssetName.Count -eq 1) {
                            $RequestFilters.assetName = $AssetName[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Asset.Name -in '$($AssetName -join "', '")'"))
                        }
                    }
                }
            }

            if ($AssetType) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'assetEntity.assetType' ate '$($AssetType -join '|')'" }
                    'WS50' { $RequestFilters.assetType = $AssetType -join '|' }
                    'REST' {
                        if ($AssetType.Count -eq 1) {
                            $RequestFilters.asset = @{type = $AssetType[0] }
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Asset.Type -in '$($AssetType -join "', '")'"))
                        }
                    }
                    'WS47' {
                        if ($AssetType.Count -eq 1) {
                            $RequestFilters.assetType = $AssetType[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Asset.Type -in '$($AssetType -join "', '")'"))
                        }
                    }
                }
            }

            if ($AssetClass) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'assetEntity.Asset Class' ate '$($AssetClass -join '|')'" }
                    { $_ -in 'REST', 'WS50', 'WS47' } { $TaskFilters.Add([ScriptBlock]::Create("`$_.Asset.Class -in '$($AssetClass -join "', '")'")) }
                }
            }

            if ($ActionName) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'apiAction.name' ate '$($ActionName -join '|')'" }
                    'WS50' { $RequestFilters.apiAction = $ActionName -join '|' }
                    'REST' { $TaskFilters.Add([ScriptBlock]::Create("`$_.Action.Name -in '$($ActionName -join "', '")'")) }
                    'WS47' {
                        if ($ActionName.Count -eq 1) {
                            $RequestFilters.apiAction = $ActionName[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Action.Name -in '$($ActionName -join "', '")'"))
                        }
                    }
                }
            }

            if ($Category) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'category' ate '$($Category -join '|')'" }
                    'WS50' { $RequestFilters.category = $Category -join '|' }
                    { $_ -in 'REST', 'WS47' } {
                        if ($Category.Count -eq 1) {
                            $RequestFilters.category = $Category[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Category -in '$($Category -join "', '")'"))
                        }
                    }
                }
            }

            if ($Title) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'comment' ate '$($Title -join '|')'" }
                    'WS50' { $RequestFilters.comment = $Title -join '|' }
                    'REST' {
                        if ($Title.Count -eq 1) {
                            $RequestFilters.title = $Title[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Title -match '$(($Title -join '|') -replace '(?<!\.)\*', '.*' -replace '%', '.*')'"))
                        }
                    }
                    'WS47' {
                        if ($Title.Count -eq 1) {
                            $RequestFilters.category = $Title[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Title -match '$(($Title -join '|') -replace '(?<!\.)\*', '.*' -replace '%', '.*')'"))
                        }
                    }
                }
            }

            if ($Team) {
                switch ($Endpoint) {
                    'TMQL' { $RequestFilters += "'role' ate '$($Team -join '|')'" }
                    'WS50' { $RequestFilters.role = $Team -join '|' }
                    'REST' {
                        if ($Team.Count -eq 1) {
                            $RequestFilters.team = $Team[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Team -in '$($Team -join "', '")'"))
                        }
                    }
                    'WS47' {
                        if ($Title.Count -eq 1) {
                            $RequestFilters.role = $Team[0]
                        } else {
                            $TaskFilters.Add([ScriptBlock]::Create("`$_.Team -in '$($Team -join "', '")'"))
                        }
                    }
                }
            }

            Write-Debug "Request Filters: $($RequestFilters -is [Hashtable] ? ($RequestFilters | ConvertTo-Json) : ($RequestFilters -join "`n"))"

            Write-Verbose "Requesting Tasks from TransitionManager"
            switch ($Endpoint) {
                'TMQL' {
                    $Tasks.AddRange((Get-FilteredTasksTMQL -Filters $RequestFilters))
                }
                'REST' {
                    $Tasks.AddRange((Get-FilteredTasksAPI -Filters $RequestFilters))
                }
                'WS50' {
                    $Tasks.AddRange((Get-FilteredTasksWS -Filters $RequestFilters))
                }
                'WS47' {
                    $Tasks.AddRange((Get-FilteredTasksWS -Filters $RequestFilters))
                }
            }
        }

        # Apply any necessary post-request filters to the tasks
        Write-Verbose "Applying additional filters to Tasks"
        Write-Debug "Task Filters:`n$($TaskFilters -join "`n")"
        if ($TaskFilters.Count -gt 0) {
            $FilteredTasks = $Tasks
            foreach ($Filter in $TaskFilters) {
                $FilteredTasks = $FilteredTasks | Where-Object -FilterScript $Filter
            }
            $Tasks = $FilteredTasks
        }

        # Web service and REST API don't return a TaskSpec
        if (($Tasks.Schema -contains 1) -and $TaskSpecId.Count -eq 1) {
            $Tasks | ForEach-Object { $_.TaskSpec = $TaskSpecId[0] }
        }

        $Tasks
    }
}


function Update-TMTask {
    <#
    .SYNOPSIS
    Updates a Task in TransitionManager
 
    .DESCRIPTION
    This function will update a Task in TransitionManager using a TMTask object that represents
    the desired changes
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Task
    The TMTask object representing the required changes
 
    .PARAMETER Note
    A note to be added to the updated Task
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .PARAMETER Passthru
    Switch indicating that the Task should be returned after being updated
 
    .EXAMPLE
    # Get an existing Task from TransitionManager
    $Task = Get-TMTask -TMSession TMAD50 -TaskNumber 1
 
    # Change the Action associated with the Task
    $Task.Action.Id = 175
 
    # Remove the user assignment
    $Task.AssignedTo.Id = 0
 
    # Set the Task's status to Pending
    $Task.Status = 'Pending'
 
    # Change the Asset associated with the Task
    $Task.Asset.Id = 232053
 
    # Use the updated TMTask object to commit the changes to TransitionManager
    Update-TMTask -TMSession TMAD50 -Task $Task
 
    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none
 
    .NOTES
    Below are the available Task properties that can be updated along with the associated
    TMTask property to be changed:
 
    Action: TMTask.Action.Id
    Asset: TMTask.Asset.Id
    Event: TMTask.Event.Id
    AssignedTo: TMTask.AssignedTo.Id
    Category: TMTask.Category
    Title: TMTask.Title
    HardAssigned: TMTask.HardAssigned
    InstructionsLink: TMTask.InstructionsLink
    PercentageComplete: TMTask.PercentageComplete
    Priority: TMTask.Priority
    Team: TMTask.Team
    Status: TMTask.Status
    SendNotification: TMTask.SendNotification
    Project: TMTask.Project.Id
    predecessors: TMTask.Predecessors
    successors: TMTask.Successors
    #>


    [CmdletBinding()]
    [Alias('Set-TMTask')]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $false)]
        [String]$Status,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru,

        [Parameter(Mandatory = $false)]
        [Switch]$UpdateTaskDependencies
    )


    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)
    }

    process {
        if ($TMSession.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri                = "https://$($TMSession.TMServer)/tdstm/api/task/$($Task.Id)"
                Method             = 'PUT'
                WebSession         = $TMSession.TMRestSession
                SkipHttpErrorCheck = $true
                StatusCodeVariable = 'StatusCode'
                Body               = ($Task.GetApiUpdateObject($Note, $Status, $UpdateTaskDependencies.IsPresent) | ConvertTo-Json -Depth 3 -Compress)
            }

            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($StatusCode -in 200, 204) {
                    if ($Passthru) {
                        [TMTask]::new($Response)
                    }
                } elseif (-not [String]::IsNullOrWhiteSpace($Response)) {
                    throw $Response
                } else {
                    throw "The response status code $StatusCode does not indicate success."
                }
            } catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        } else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/ws/task/saveTask"
                Method     = 'POST'
                WebSession = $TMSession.TMWebSession
                Body       = ($Task.GetWSUpdateObject($UpdateTaskDependencies.IsPresent) | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if (-not [String]::IsNullOrWhiteSpace($Note)) {
                        Add-TMTaskNote -TMSession $TMSession -Id $Task.Id -Note $Note
                    }
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        } catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                } else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function New-TMTask {
    <#
    .SYNOPSIS
    Creates a new Task in TransitionManager
 
    .DESCRIPTION
    This function will create a new Task in TransitionManager either by using the specified
    properties or by using a TMTask object
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Task
    A TMTask object representing the new Task to be created
 
    .PARAMETER Title
    The title of the new Task
 
    .PARAMETER EventId
    The Id of the Event in which to place the new Task
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project in which to place the new Task. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Status
    The status of the new Task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER Team
    The team to be assigned to the new Task
 
    .PARAMETER Priority
    The priority of the new Task
 
    .PARAMETER InstructionsLink
    The instructions link to place on the new Task
 
    .PARAMETER Duration
    The duration of the new task
 
    .PARAMETER SendNotification
    Indicates if the new Task should send notifications
 
    .PARAMETER Category
    The category of the new Task
 
    .PARAMETER AssignedToId
    The Id of the person that should be assigned to the new Task
 
    .PARAMETER AssetId
    The Id of the Asset to be associated with the new Task
 
    .PARAMETER ActionId
    The Id of the Action to be associated with the new Task
 
    .PARAMETER Predecessor
    One or more Task Ids that will be linked as a predecessor on the new Task
 
    .PARAMETER Successor
    One or more Task Ids that will be linked as a succecessor on the new Task
 
    .PARAMETER Note
    A note to be added to the new Task
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .PARAMETER Passthru
    Switch indicating that the new Task should be returned after creation
 
    .EXAMPLE
    $NewTaskSplat = @{
        TMSession = "TMAD60"
        Title = "Test Task - w/ Dependencies"
        EventId = 460
        ProjectId = 6269
        Status = "Ready"
        Team = 'SYS_ADMIN'
        AssignedToId = 6246
        AssetId = 232053
        Successor = 369638, 411521
        Predecessor = 411702
        Note = "This was created via PowerShell"
        Passthru = $true
        ActionId = 178
    }
    New-TMTask @NewTaskSplat
 
    .EXAMPLE
    This example gets an existing task and then changes the associated Action
    and Title as well as removes all predecessors
 
    $Task = Get-TMTask -TMSession TMAD50 -Id $NewTask.id
    $Task.Action.Id = 177
    $Task.Title = "Copy of $($NewTask.TaskNumber)"
    $Task.Predecessors = @()
    New-TMTask -TMSession TMAD50 -Task $Task -Note "This task was created as a modified copy of $($Task.Id)"
 
 
    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByProperty')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Title,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [Int]$EventId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidStatuses } )]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [String]$Status = 'Pending',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$Team,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ValidateRange(1, 5)]
        [Int]$Priority = 3,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$InstructionsLink,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$Duration = 0,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Bool]$SendNotification = $false,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidCategories } )]
        [ValidateScript( { $_ -in [TMTask]::ValidCategories } )]
        [String]$Category = 'general',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssignedToId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssetId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$ActionId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Predecessor,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Successor,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )


    begin {

        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSession.UserContext.Project.id
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq 'ByObject') {
            $Title = $Task.Title
            $EventId = $Task.Event.Id
            $ProjectId = $Task.Project.Id
            $Status = $Task.Status
            $Team = $Task.Team
            $Priority = $Task.Priority
            $InstructionsLink = $Task.InstructionsLink
            $Category = $Task.Category
            $AssignedToId = $Task.AssignedTo.Id
            $AssetId = $Task.Asset.Id
            $ActionId = $Task.Action.Id
            $Predecessor = $Task.Predecessors.TaskId
            $Successor = $Task.Successors.TaskId
            $SendNotification = $Task.SendNotification
            $Duration = $Task.Duration
        }

        if ($TMSession.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"

            Write-Verbose "Forming web request body"
            $Body = @{
                title            = $Title
                event            = @{ id = $EventId }
                project          = $ProjectId
                status           = $Status
                priority         = $Priority
                category         = $Category
                action           = @{ id = $ActionId }
                role             = $Team
                duration         = $Duration
                instructionsLink = $InstructionsLink
                assignedTo       = $AssignedToId
                asset            = @{ id = $AssetId }
                note             = $Note
                sendNotification = $SendNotification ? 1 : 0
                predecessors     = @()
                successors       = @()
            }
            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.predecessors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.successors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/api/task"
                Method     = 'POST'
                WebSession = $TMSession.TMRestSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($Passthru) {
                    [TMTask]::new($Response)
                }
            } catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        } else {
            Write-Verbose "Using web service endpoint"
            $Body = @{
                comment          = $Title
                status           = $Status
                assignedTo       = $AssignedToId
                apiAction        = $ActionId
                apiActionId      = $ActionId
                category         = $Category
                assetEntity      = $AssetId
                moveEvent        = $EventId
                priority         = $Priority
                role             = $Team
                sendNotification = $SendNotification ? 1 : 0
                instructionsLink = $InstructionsLink
                duration         = $Duration
                durationScale    = "M"
                durationLocked   = 0
                manageDependency = 0
                taskDependency   = @()
                taskSuccessor    = @()
            }

            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.taskDependency += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.taskSuccessor += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }

            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/ws/task/saveTask"
                Method     = 'POST'
                WebSession = $TMSession.TMWebSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        } catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                } else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Remove-TMTask {
    <#
    .SYNOPSIS
    Deletes a Task from TransitionManager
 
    .DESCRIPTION
    This function will delete one or more of the specified Tasks from TransitionManager
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of the task to be deleted
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Remove-TMTask -Id 587434
 
    .EXAMPLE
    Get-TMTask -Id 129874, 458696 | Remove-TMTask
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true,
            Position = 1,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [Int[]]$Id,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $false
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)
    }

    process {
        if ($TMSession.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            foreach ($TaskId in $Id) {
                Write-Verbose "Forming web request parameters"
                $RestSplat = @{
                    Uri        = "https://$($TMSession.TMServer)/tdstm/api/task/$($Id)"
                    Method     = 'DELETE'
                    WebSession = $TMSession.TMRestSession
                }
                Write-Debug "Web Request Parameters:"
                Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
                Write-Verbose "Invoking REST method"
                try {
                    $Response = Invoke-RestMethod @RestSplat
                    Write-Debug "Response:"
                    Write-Debug ($Response | ConvertTo-Json -Depth 10)
                } catch {
                    throw "Error while deleting task: $($_.Exception.Message)"
                }
            }
        } else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/ws/asset/comment/$($Id)"
                Method     = 'DELETE'
                WebSession = $TMSession.TMWebSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function Set-TMTaskStatus {
    <#
    .SYNOPSIS
    Sets the status of a TransitionManager Task
 
    .DESCRIPTION
    This function will set/update the status of the specified Task in TransitionManager
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of Task on which the status will be set
 
    .PARAMETER Status
    The new status to set on the task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Set-TMTaskStatus -TMSession TMAD50 -Id 411521 -Status Ready
 
    .EXAMPLE
    Get-TMTask -TaskNumber 189, 2569 | Set-TMTaskStatus -Status Ready
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [Alias('State')]
        [String]$Status,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSession.UserContext.Project.id
    }

    process {
        if ($TMSession.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/api/task/$($Id)/updateStatus?status=$Status&project=$ProjectId"
                Method     = 'POST'
                WebSession = $TMSession.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            } catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        } else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/assetEntity/updateComment"
                Method     = 'POST'
                WebSession = $TMSession.TMWebSession
                Body       = (@{
                        id     = $Id
                        status = $Status
                    } | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Add-TMTaskNote {
    <#
    .SYNOPSIS
    Adds a note to the specified Task
 
    .DESCRIPTION
    This function will add the specified note to a TransitionManager Task
 
    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection
 
    .PARAMETER Id
    The Id of the Task to which the note should be added
 
    .PARAMETER Note
    The note to be added
 
    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used
 
    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints
 
    .EXAMPLE
    Add-TMTaskNote -TMSession TMAD50 -Id 12356 -Note "This task was updated via PowerShell"
 
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $false
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSession = Get-TMSession $TMSession
        Write-Debug "TMSession:"
        Write-Debug ($TMSession | ConvertTo-Json -Depth 5)

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSession.UserContext.Project.id
    }

    process {
        if ($TMSession.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSession.TMServer)/tdstm/api/task/$($Id)/addNote"
                Method     = 'POST'
                Body       = (@{
                        note    = $Note
                        project = $ProjectId
                    } | ConvertTo-Json)
                WebSession = $TMSession.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            } catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        } else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri         = "https://$($TMSession.TMServer)/tdstm/ws/task/$($Id)/addNote"
                Method      = 'POST'
                Body        = (@{
                        note = $Note
                    } | ConvertTo-Json)
                WebSession  = $TMSession.TMWebSession
                ContentType = 'application/json'
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        }
    }
}