Scripts/Get-BPAAgent.ps1

function Get-BPAAgent {
    <#
        .SYNOPSIS
            Gets AutoMate BPA agents.
 
        .DESCRIPTION
            Get-BPAAgent gets agent objects from AutoMate BPA. Get-BPAAgent can receive items on the pipeline and return related objects.
 
        .PARAMETER InputObject
            The object(s) to use in search for agents.
 
        .PARAMETER Name
            The name of the agent (case sensitive). Wildcard characters can be escaped using the ` character. If using escaped wildcards, the string
            must be wrapped in single quotes. For example: Get-BPAAgent -Name '`[Test`]'
 
        .PARAMETER ID
            The ID of the agent.
 
        .PARAMETER FilterSet
            The parameters to filter the search on. Supply hashtable(s) with the following properties: Property, Comparator, Value.
            Valid values for the Comparator are: =, !=, <, >, contains (default - no need to supply Comparator when using 'contains')
 
        .PARAMETER FilterSetMode
            If multiple filter sets are provided, FilterSetMode determines if the filter sets should be evaluated with an AND or an OR
 
        .PARAMETER SortProperty
            The object property to sort results on. Do not use BPAServer or TypeName, since those are custom properties added by this module, and not exposed in the API.
 
        .PARAMETER SortDescending
            If specified, this will sort the output on the specified SortProperty in descending order. Otherwise, ascending order is assumed.
 
        .PARAMETER BPAServer
            The AutoMate BPA management server.
 
        .INPUTS
            Agents related to the following objects can be retrieved by this function:
            Workflow
            Task
            Condition
            Process
            AgentGroup
            Folder
            Instance
 
        .EXAMPLE
            # Get agent "agent01"
            Get-BPAAgent "agent01"
 
        .EXAMPLE
            # Get agents in agent group "group01"
            Get-BPAAgentGroup "group01" | Get-BPAAgent
 
        .EXAMPLE
            # Get agents configured within any workflow for the condition "My Condition"
            Get-BPACondition "My Condition" | Get-BPAAgent
 
        .EXAMPLE
            # Get agents using filter sets
            Get-BPAAgent -FilterSet @{ Property = "Enabled"; Comparator = "="; Value = "true"}
 
        .NOTES
            Author(s): : David Seibel
            Contributor(s) :
            Date Created : 08/24/2016
            Date Modified : 05/03/2018
 
        .LINK
            https://github.com/davidseibel/PoshBPA
    #>

    [CmdletBinding(DefaultParameterSetName = "All")]
    [OutputType([System.Object[]])]
    param(
        [Parameter(ValueFromPipeline = $true, ParameterSetName = "ByPipeline")]
        [ValidateNotNullOrEmpty()]
        $InputObject,

        [Parameter(Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(ParameterSetName = "ByID")]
        [ValidateNotNullOrEmpty()]
        [string]$ID,
        
        [Hashtable[]]$FilterSet,

        [ValidateSet("And","Or")]
        [string]$FilterSetMode = "And",

        [ValidateNotNullOrEmpty()]
        [BPAAgentType]$Type = [BPAAgentType]::All,

        [ValidateNotNullOrEmpty()]
        [string[]]$SortProperty = "Name",

        [switch]$SortDescending = $false,

        [ValidateNotNullOrEmpty()]
        [string]$BPAServer
    )

    BEGIN {
        # If the server is specified, or only 1 server is connected, don't show it. Otherwise, show the server.
        if ($PSCmdlet.ParameterSetName -eq "ByID" -and (-not $PSBoundParameters.ContainsKey("BPAServer")) -and ($global:BPAConnectionInfo.Count -gt 1)) {
            throw "When searching by ID: 1) BPAServer must be specified, OR 2) only one server can be connected."
        }
        $splat = @{
            RestMethod = "Get"
            BPAServer  = $BPAServer
        }
        $result = @()
        $workflowCache = @{}
        $agentCache = @{}
        if ($PSBoundParameters.ContainsKey("Name") -and (-not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Name))) {
            $FilterSet += @{Property = "Name"; Comparator = "="; Value = [System.Management.Automation.WildcardPattern]::Unescape($Name)}
        } elseif ($PSBoundParameters.ContainsKey("Name") -and [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Name)) {
            try   { "" -like $Name | Out-Null } # Test wildcard string
            catch { throw }                     # Throw error if wildcard invalid
            $splat += @{ FilterScript = {$_.Name -like $Name} }
        }
        if ($Type -ne [BPAAgentType]::All) {
            $FilterSet += @{Property = "AgentType"; Comparator = "="; Value = $Type.value__}
        }
    }

    PROCESS {
        switch($PSCmdlet.ParameterSetName) {
            "All" {
                $splat += @{ Resource = Format-BPAUri -Path "agents/list" -FilterSet $FilterSet -FilterSetMode $FilterSetMode -SortProperty $SortProperty -SortDescending:$SortDescending.ToBool() }
                $result = Invoke-BPARestMethod @splat
            }
            "ByID" {
                if ($PSBoundParameters.ContainsKey("Type")) {
                    Write-Warning "Parameter -Type is ignored when querying by ID."
                }
                $splat += @{ Resource = "agents/$ID/get" }
                $result = Invoke-BPARestMethod @splat
            }
            "ByPipeline" {
                foreach ($obj in $InputObject) {
                    $tempSplat = $splat
                    if (-not $tempSplat.ContainsKey("BPAServer")) {
                        $tempSplat += @{ BPAServer = $obj.BPAServer }
                    } else { 
                        $tempSplat["BPAServer"] = $obj.BPAServer
                    }
                    if (-not $agentCache.ContainsKey($obj.BPAServer)) {
                        Write-Verbose "Caching agent objects for server $($obj.BPAServer) for better performance"
                        $agentCache.Add($obj.BPAServer, (Get-BPAAgent -FilterSet $FilterSet -FilterSetMode $FilterSetMode -SortProperty $SortProperty -SortDescending:$SortDescending.ToBool() -BPAServer $obj.BPAServer))
                    }
                    switch ($obj.TypeName) {
                        "Workflow" {
                            # Get agents that are assigned to items within the provided workflow(s)
                            foreach ($item in $obj.Items | Where-Object {($_.ConstructType -as [BPAConstructType]) -in ("Condition","Task")}) {
                                if ($Type -eq [BPAAgentType]::All) {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID}
                                } else {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID -and $_.AgentType -eq $Type.value__}
                                }
                            }
                            foreach ($trigger in $obj.Triggers | Where-Object {($_.TriggerType -as [BPATriggerType]) -notin ("Schedule")}) {
                                if ($Type -eq [BPAAgentType]::All) {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $trigger.AgentID}
                                } else {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $trigger.AgentID -and $_.AgentType -eq $Type.value__}
                                }
                            }
                        }
                        "Task" {
                            if (-not $workflowCache.ContainsKey($obj.BPAServer)) {
                                Write-Verbose "Caching workflow objects for server $($obj.BPAServer) for better performance"
                                $workflowCache.Add($obj.BPAServer, (Get-BPAWorkflow -BPAServer $obj.BPAServer))
                            }
                            # Get agents that are assigned to the provided task(s) within workflows
                            foreach ($workflow in $workflowCache[$obj.BPAServer]) {
                                foreach ($item in $workflow.Items) {
                                    switch ($item.ConstructType -as [BPAConstructType]) {
                                        "Task" {
                                            if ($item.ConstructID -eq $obj.ID) {
                                                if ($Type -eq [BPAAgentType]::All) {
                                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID}
                                                } else {
                                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID -and $_.AgentType -eq $Type.value__}
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        "Process" {
                            if (-not $workflowCache.ContainsKey($obj.BPAServer)) {
                                Write-Verbose "Caching workflow objects for server $($obj.BPAServer) for better performance"
                                $workflowCache.Add($obj.BPAServer, (Get-BPAWorkflow -BPAServer $obj.BPAServer))
                            }
                            # Get agents that are assigned to the provided task(s) within workflows
                            foreach ($workflow in $workflowCache[$obj.BPAServer]) {
                                foreach ($item in $workflow.Items) {
                                    switch ($item.ConstructType -as [BPAConstructType]) {
                                        "Process" {
                                            if ($item.ConstructID -eq $obj.ID) {
                                                if ($Type -eq [BPAAgentType]::All) {
                                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID}
                                                } else {
                                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID -and $_.AgentType -eq $Type.value__}
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        "Condition" {
                            if (-not $workflowCache.ContainsKey($obj.BPAServer)) {
                                Write-Verbose "Caching workflow objects for server $($obj.BPAServer) for better performance"
                                $workflowCache.Add($obj.BPAServer, (Get-BPAWorkflow -BPAServer $obj.BPAServer))
                            }
                            # Get agent groups that are assigned to the provided task(s) within workflows
                            foreach ($workflow in $workflowCache[$obj.BPAServer]) {
                                foreach ($trigger in $workflow.Triggers) {
                                    if ($trigger.ConstructID -eq $obj.ID) {
                                        if ($trigger.AgentID) {
                                            if ($Type -eq [BPAAgentType]::All) {
                                                $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID}
                                            } else {
                                                $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $item.AgentID -and $_.AgentType -eq $Type.value__}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        "AgentGroup" {
                            # Get agents contained within the provided agent group(s)
                            foreach ($agentID in $obj.AgentIDs) {
                                if ($Type -eq [BPAAgentType]::All) {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $agentID}
                                } else {
                                    $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ID -eq $agentID -and $_.AgentType -eq $Type.value__}
                                }
                            }
                        }
                        "Folder" {
                            if ($Type -eq [BPAAgentType]::All) {
                                # Get agents contained within the provided folder(s)
                                $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ParentID -eq $obj.ID}
                            } else {
                                $result += $agentCache[$obj.BPAServer] | Where-Object {$_.ParentID -eq $obj.ID -and $_.AgentType -eq $Type.value__}
                            }
                        }
                        "Instance" {
                            # If the AgentID property is not specified, it's probably a workflow instance, which can be ignored
                            if ($obj.AgentID -ne "") {
                                # Get agents that host the specified instance(s)
                                $result += Get-BPAAgent -ID $obj.AgentID
                            }
                        }
                        default {
                            $unsupportedType = $obj.GetType().FullName
                            if ($_) { 
                                $unsupportedType = $_ 
                            } elseif (($null -ne $obj.Type) -and ($obj.Type -ne "")) {
                                $unsupportedType = $obj.Type
                            }
                            Write-Error -Message "Unsupported input type '$unsupportedType' encountered!" -TargetObject $obj
                        }
                    }
                }
            }
        }  
    }  

    END {
        $SortProperty += "BPAServer", "ID"
        return $result | Sort-Object $SortProperty -Unique -Descending:$SortDescending.ToBool()
    }
}