Public/Get-PdqPackageLibraryCatalog.ps1

<#
.SYNOPSIS
Retrieves the Package Library catalog from the PDQ web API.
 
.DESCRIPTION
The catalog is large, so this function caches it to avoid re-downloading it on successive calls.
 
.INPUTS
None.
 
.OUTPUTS
System.Xml.XmlDocument
 
.EXAMPLE
Get-PdqPackageLibraryCatalog
Retrieves the Package Library catalog and emits it as an XmlDocument object.
#>


function Get-PdqPackageLibraryCatalog {

    [CmdletBinding()]
    param (
        # How long you want to wait before downloading a fresh copy of the Package Library catalog.
        [UInt32]$CacheTimeoutSeconds = 600
    )
    
    $CacheDirectory = "$env:TEMP\PdqStuff"
    $CacheFullPath = "$CacheDirectory\PackageLibraryCatalog.xml"

    if ( -not (Test-Path $CacheDirectory) ) {

        $null = New-Item -ItemType 'Directory' -Path $CacheDirectory
        Write-Verbose "Created $CacheDirectory"

    }

    # Assume the cache is invalid until proven otherwise.
    $InvalidCache = $true
    
    if ( Test-Path $CacheFullPath ) {

        [UInt32]$CacheAge = ( (Get-Date) - (Get-ItemProperty -Path $CacheFullPath).LastWriteTime ).TotalSeconds
        Write-Verbose "Age of cached catalog = $CacheAge seconds"

        if ( $CacheAge -lt $CacheTimeoutSeconds ) {

            $InvalidCache = $false

        } else {

            Write-Verbose "Cache age of $CacheAge exceeds timeout of $CacheTimeoutSeconds"

        }

    }
    
    if ( $InvalidCache ) {

        Write-Verbose 'Downloading fresh catalog'
        $LibraryCatalog = Invoke-RestMethod -Uri 'https://library.pdq.com/PackageLibrary'
        $LibraryCatalog.Save($CacheFullPath)

    } else {

        Write-Verbose 'Using cached catalog'
        [XML]$LibraryCatalog = Get-Content -Raw -Path $CacheFullPath

    }

    $LibraryCatalog

}