Public/Get-DuneResource.ps1

<#
.SYNOPSIS
Retrieve resources.

.DESCRIPTION
Gets resource objects and supports multiple parameter sets to find resources by `Id`, `ExtId`, `Collection`, `Deployment`, `ResourceGroup`, `ResourceProvider`, `ComputeNode`, `ResourceId`, `Job`, or by name. Additional filters include `DisplayName`, operational `State`, raw output and include-deleted flag. Returns `DuneResource` objects by default.

.PARAMETER Name
Filter resources by name (supports wildcards). Position 0 in the default parameter set.

.PARAMETER Id
The GUID of a resource. Use the `Id` parameter set to retrieve a specific resource.

.PARAMETER ExtId
Filter by external identifier.

.PARAMETER Collection
A `DuneCollection` object; returns resources in the supplied collection (pipeline input supported).

.PARAMETER Deployment
A `DuneDeployment` object; returns resources for the supplied deployment (pipeline input supported).

.PARAMETER ResourceGroup
A `DuneResourceGroup` object; returns resources in the supplied resource group (pipeline input supported).

.PARAMETER ResourceProvider
A `DuneResourceProvider` object; filter resources by provider (pipeline input supported).

.PARAMETER ComputeNode
A `DuneComputeNode` object; returns resources hosted on the provided compute node (pipeline input supported).

.PARAMETER ResourceId
Alternate resource id parameter accepted from pipeline by property name.

.PARAMETER Job
A `DuneJob` object; returns resources referenced by the supplied job (pipeline input supported).

.PARAMETER ActionAssignment
A `DuneActionAssignment` object; returns resources for the supplied action assignment (pipeline input supported).

.PARAMETER DisplayName
Filter by display name (supports wildcards).

.PARAMETER State
Filter by operational state (`OperationalStates`).

.PARAMETER Raw
If set, returns raw API objects instead of `DuneResource` objects.

.PARAMETER IncludeDeleted
Include deleted resources in results.

.PARAMETER CreatedAfter
Only return resources created after the given date/time (server-side filter, `Created > CreatedAfter`). Local times are converted to UTC.

.PARAMETER CreatedBefore
Only return resources created before the given date/time (server-side filter, `Created < CreatedBefore`). Local times are converted to UTC.

.EXAMPLE
PS> Get-DuneResource -Name "web*"
Return resources with names matching `web*`.

.EXAMPLE
PS> Get-DuneResource -Id 3d8f6b5a-...
Return the resource with the specified `Id`.

.EXAMPLE
PS> Get-DuneDeployment -Name "app" | Get-DuneResource
Pipeline example using the `Deployment` parameter set.
#>

function Get-DuneResource {
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [Parameter(Position = 0)]
        [string]$Name,

        [Parameter(ParameterSetName = "Id")]
        [guid]$Id,

        [Parameter(ParameterSetName = "ExtId")]
        [string]$ExtId,

        [Parameter(ParameterSetName = "Collection", ValueFromPipeline)]
        [DuneCollection]$Collection,

        [Parameter(ParameterSetName = "Deployment", ValueFromPipeline)]
        [DuneDeployment]$Deployment,

        [Parameter(ParameterSetName = "ResourceGroup", ValueFromPipeline)]
        [DuneResourceGroup]$ResourceGroup,

        [Parameter(ParameterSetName = "ResourceProvider", ValueFromPipeline)]
        [DuneResourceProvider]$ResourceProvider,

        [Parameter(ParameterSetName = "ComputeNode", ValueFromPipeline)]
        [DuneComputeNode]$ComputeNode,

        [Parameter(ParameterSetName = "ResourceId", ValueFromPipelineByPropertyName)]
        [guid]$ResourceId,

        [Parameter(ParameterSetName = "Job", ValueFromPipeline)]
        [DuneJob]$Job,

        [Parameter(ParameterSetName = "ActionAssignment", ValueFromPipeline)]
        [DuneActionAssignment]$ActionAssignment,

        [Parameter()]
        [string]$DisplayName,

        [Parameter()]
        [OperationalStates]$State,

        [Parameter()]
        [datetime]$CreatedAfter,

        [Parameter()]
        [datetime]$CreatedBefore,

        [Parameter()]
        [switch]$Raw,

        [Parameter()]
        [switch]$ExcludeReferencedObjects,

        [Parameter()]
        [switch]$IncludeDeleted
    )

    begin {
        Write-Debug "$($MyInvocation.MyCommand)|begin"
        $ReturnObjects = @()
        $ProcessedUrls = @()
        $BaseUri = 'resources'
        $Method = 'GET'
    }

    process {
        Write-Debug "$($MyInvocation.MyCommand)|process|$($PSCmdlet.ParameterSetName)"

        # Build Uri
        $Uri = switch ($PSCmdlet.ParameterSetName) {
            'Id' { '{0}/{1}' -f $BaseUri, $Id }
            'ResourceGroup' { '{0}?ParentId={1}' -f $BaseUri, $ResourceGroup.Id }
            'Collection' { '{0}?CollectionId={1}' -f $BaseUri, $Collection.Id }
            'Deployment' { '{0}?DeploymentId={1}' -f $BaseUri, $Deployment.Id }
            'ComputeNode' { '{0}/{1}' -f $BaseUri, $ComputeNode.id }
            'ResourceId' { '{0}/{1}' -f $BaseUri, $ResourceId }
            'ExtId' { '{0}?ExtIdIEquals={1}' -f $BaseUri, $ExtId }
            'ResourceProvider' { '{0}?ResourceProviderId={1}' -f $BaseUri, $ResourceProvider.id }
            'Job' {
                if ($Job.ConfigItemType -eq "Resource") {
                    '{0}/{1}' -f $BaseUri, $Job.ConfigItemId
                }
                else {
                    Write-Warning "Wrong ConfigItemType $($Job.ConfigItemId) for Job $($Job.Name) (id: $($Job.Id))"
                    return
                }
            }
            'ActionAssignment' {
                if ($ActionAssignment.Scope -ne 'Resource') { Write-Warning "Unable to load DuneResource for ActionAssignment ""$($ActionAssignment.Name)"" as its for Scope $($ActionAssignment.Scope)"; return }
                '{0}/{1}' -f $BaseUri, $ActionAssignment.ConfigItemId
            }
            Default { '{0}' -f $BaseUri }
        }
        if ($Name) {
            $Uri = $Uri | Add-UriQueryParam "NameILike=$Name" -ConvertWildcards
        }
        if ($DisplayName) {
            $Uri = $Uri | Add-UriQueryParam "DisplayNameILike=$DisplayName" -ConvertWildcards
        }
        if ($PSBoundParameters.ContainsKey('State')) {
            $Uri = $Uri | Add-UriQueryParam "State=$($State.ToString())"
        }
        if ($IncludeDeleted) {
            $Uri = $Uri | Add-UriQueryParam "IncludeDeleted=1"
        }
        if ($PSCmdlet.ParameterSetName -notin 'Id', 'ComputeNode', 'ResourceId' -or -not $ExcludeReferencedObjects) {
            $Uri = $Uri | Add-UriQueryParam "IncludeReferencedObjects=1"
        }
        if ($PSBoundParameters.ContainsKey('CreatedAfter')) {
            $Uri = $Uri | Add-UriQueryParam "CreatedGreaterThan=$([uri]::EscapeDataString($CreatedAfter.ToUniversalTime().ToString('o')))"
        }
        if ($PSBoundParameters.ContainsKey('CreatedBefore')) {
            $Uri = $Uri | Add-UriQueryParam "CreatedLessThan=$([uri]::EscapeDataString($CreatedBefore.ToUniversalTime().ToString('o')))"
        }

        # ApiCall Cache
        if ($ProcessedUrls -notcontains $Uri) {
            try {
                # ApiCall and Object conversion
                $ResultItems = Invoke-DuneApiRequest -Uri $Uri -Method $Method -ExtractItems
                $ProcessedUrls += $Uri
                $ReturnObjects += $ResultItems | ForEach-Object {
                    if ($Raw) {
                        $_
                    }
                    else {
                        ConvertTo-DuneClassObject -Class DuneResource -InputObject $_ #-AbstractClass "Deployment"
                    }
                }
            }
            catch {
                throw $_
            }
        }
        else {
            Write-Debug "$($MyInvocation.MyCommand)|process|ApiCall Cache hit: DuneApiRequest for $Uri already invoked"
        }
    }

    end {
        Write-Debug "$($MyInvocation.MyCommand)|end"
        return $ReturnObjects | Sort-Object -Unique Id | Sort-Object name
    }
}