Public/Enable-PdqPackageAlwaysPrioritized.ps1

<#
.SYNOPSIS
Allows packages to be tagged so their deployments will always be prioritized.
 
.DESCRIPTION
To tag a package, add a Step (any Type will work), and set the Title to "Always Prioritized".
I recommend disabling the Step so it doesn't slow down deployments.
 
.INPUTS
None.
 
.OUTPUTS
None.
 
.EXAMPLE
Enable-PdqPackageAlwaysPrioritized
Adds a trigger to your database.
#>


function Enable-PdqPackageAlwaysPrioritized {
    
    [CmdletBinding()]
    param (
        # The path to the currently active database will be retrieved by default.
        # You can use this parameter if you wish to run this function against a different database.
        [String]$DatabasePath,

        # Deletes the trigger from your database.
        [Switch]$RemoveTrigger
    )

    Write-Warning 'This function must be run after every PDQ Deploy update.'

    $TriggerName = 'prioritize_tagged_packages'
    $TriggerQuery = @"
CREATE TRIGGER
    $TriggerName
AFTER INSERT
    ON
        DeploymentComputers
WHEN
    NEW.DeploymentId IN (
        SELECT
            DeploymentId
        FROM
            Deployments
        INNER JOIN
            PackageSteps USING (PackageDefinitionId)
        WHERE
            PackageSteps.Title = 'Always Prioritized'
    )
BEGIN
    UPDATE
        DeploymentComputers
    SET
        Prioritized = datetime('now')
    WHERE
        DeploymentComputerId = NEW.DeploymentComputerId
    ;
END;
"@


    Try {

        $CloseConnection = Open-PdqSqlConnection -Product 'Deploy' -DatabasePath $DatabasePath

        # Prioritization was introduced in 18.1.0.0.
        Assert-PdqMinimumVersion -Product 'Deploy' -MinimumVersion '18.1.0.0'

        $null = Invoke-SqlUpdate -Query "DROP TRIGGER IF EXISTS $TriggerName" -ConnectionName 'Deploy'
        Write-Verbose "Trigger $TriggerName was deleted, if it existed."

        if ( $RemoveTrigger ) {

            Break

        }

        $null = Invoke-SqlUpdate -Query $TriggerQuery -ConnectionName 'Deploy'
        Write-Verbose "Trigger $TriggerName created."

        Write-Host ''
        Write-Host 'Success! Please run the following to learn how to tag packages:'
        Write-Host 'Get-Help Enable-PdqPackageAlwaysPrioritized'

    } Finally {

        Close-PdqSqlConnection -Product 'Deploy' -CloseConnection $CloseConnection

    }

}