Public/Set-PdqCustomVariable.ps1

<#
.SYNOPSIS
Creates or updates a Custom Variable in Deploy or Inventory.
 
.INPUTS
None.
 
.OUTPUTS
None.
 
.EXAMPLE
Set-PdqCustomVariable -Product 'Deploy' -Name 'UniverseAnswer' -Value 42
Creates or updates @(UniverseAnswer) in Deploy and sets its value to 42.
#>

function Set-PdqCustomVariable {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        # The name of the Variable you would like to create or update.
        [String]$Name,

        # The data you would like to store in the Variable.
        [String]$Value,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Deploy', 'Inventory')]
        # The PDQ application you would like to execute this function against.
        [String]$Product,

        # 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
    )

    switch (Test-PdqVariableName -Name $Name) {
        'Bare' {
            $CustomName = Convert-PdqVariableType -Name $Name -Type 'Custom'
        }
        'Custom' {
            $CustomName = $Name
            # Strip the formatting characters out of the name.
            # The database doesn't store the names with the formatting characters.
            $Name = Convert-PdqVariableType -Name $Name -Type 'Bare'
        }
        'System' {
            throw 'This function cannot create System Variables.'
        }
    }

    $TimeStamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'

    $VariableExists = Get-PdqVariable -Name $CustomName -Product $Product -DatabasePath $DatabasePath -ErrorAction 'SilentlyContinue'
    if ( $VariableExists ) {

        $Query = "UPDATE CustomVariables SET (Value, Created, Modified) = ('$Value', '$TimeStamp', '$TimeStamp') WHERE Name = '$Name';"
        Write-Verbose "Updating: $Name"

    } else {

        $Query = "INSERT INTO CustomVariables (Name, Value, Created, Modified) VALUES ('$Name', '$Value', '$TimeStamp', '$TimeStamp');"
        Write-Verbose "Creating: $Name"

    }

    $null = Invoke-PdqSqlQuery -Product $Product -DatabasePath $DatabasePath -Query $Query -QueryType 'Update'

    Write-Host ''
    Write-Host "Success! Please refresh the PDQ $Product console."

}