Variables.psm1

<#
.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()]
    param (
        # The variable to be assigned a default value if it is null.
        [Parameter(ValueFromPipeline=$true)]
        [AllowNull()]
        $variable,

        # The default value for the variable.
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNull()]
        $defaultValue
    )

    # 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 (!$variable) {
        Write-Verbose "Setting global variable '$($externalVariableName)' to the default value '$($defaultValue)'."
        Invoke-Expression "`$Global:$($externalVariableName) = `$defaultValue"
    }
}