Functions/Set-DefaultValue.ps1

<#
.SYNOPSIS
    This function sets a variable to a specified default value in the global scope if it is null.
.EXAMPLE
    $var = $null
    $var | Set-DefaultValue 42 # $var is now 42
.EXAMPLE
    $var = 5
    $var | Set-DefaultValue 42 # $var is still 5
#>

function Set-DefaultValue {
    [CmdletBinding(PositionalBinding=$true)]
    param (
        # The default value for the variable.
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        $defaultValue,

        # The variable to be assigned a default value if it is null.
        [Parameter(ValueFromPipeline=$true)]
        [AllowNull()]
        $variable
    )

    # Retrieve the line containing the invocation of this function
    $invocationLine = ((Get-Variable -Scope 0) | Where-Object { $_.Name -eq "MyInvocation" }).Value.Line

    # This function should be passed the external variable using the pipeline
    # If not, we cannot extract the name of the external variable
    if ($invocationLine.IndexOf("|") -eq -1) {
        throw "Set-DefaultValue should be given the variable through the pipeline - `$variable | Set-DefaultValue `$defaultValue."
    }

    # Extract the name of the external variable
    $externalVariableName = $invocationLine.Split("|")[0].Trim().TrimStart("$")

    # Set the external variable to its default value
    if ($null -eq $variable) {
        # Remove the variable from all scopes to ensure that only the global one will exist
        Remove-Variable -Name $externalVariableName -Scope Local -Force -Confirm:$false -ErrorAction SilentlyContinue
        Remove-Variable -Name $externalVariableName -Scope Script -Force -Confirm:$false -ErrorAction SilentlyContinue
        Remove-Variable -Name $externalVariableName -Scope 0 -Force -Confirm:$false -ErrorAction SilentlyContinue
        Remove-Variable -Name $externalVariableName -Scope 1 -Force -Confirm:$false -ErrorAction SilentlyContinue

        # Set the global variable to the default value
        Write-Verbose "Setting global variable '$($externalVariableName)' to the default value '$($defaultValue)'."
        Invoke-Expression "`$Global:$($externalVariableName) = `$defaultValue"
    }
}