Public/Join-SpecPathWithEnvironmentVariable.ps1

function Join-SpecPathWithEnvironmentVariable {
    <#
    .SYNOPSIS
    Joins a path with a dynamically retrieved environment variable value using Join-Path.
 
    .DESCRIPTION
    This function takes a path containing an environment variable (either single-quoted or double-quoted)
    or a plain string, and a child path. It evaluates the environment variable and joins it with the child
    path using Join-Path.
 
    .PARAMETER Path
    The path containing an environment variable (e.g., '$env:ProgramData', 'C:\MyPath', etc.).
 
    .PARAMETER ChildPath
    The child path to be joined with the environment variable or the plain string path.
 
    .EXAMPLE
    Join-SpecPathWithEnvironmentVariable -Path '$env:ProgramData' -ChildPath 'myfile.ico'
    # Output: C:\ProgramData\myfile.ico
 
    Join-SpecPathWithEnvironmentVariable -Path 'C:\MyPath' -ChildPath 'myfile.ico'
    # Output: C:\MyPath\myfile.ico
 
    .NOTES
    Author : owen.heaume
    Version : 1.0.0
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Path,

        [Parameter(Mandatory = $true)]
        [string]$ChildPath
    )

    try {
        # Expand environment variables and evaluate the path
        $evaluatedPath = [System.Environment]::ExpandEnvironmentVariables($ExecutionContext.InvokeCommand.ExpandString($Path))

        # Join the environment variable value or plain string with the child path
        $fullPath = Join-Path -Path $evaluatedPath -ChildPath $ChildPath -ErrorAction Stop

        # Output the full path
        return $fullPath
    } catch {
        # Handle errors and provide meaningful error message
        Write-Error "Error occurred: $_"
        return 1
    }
}