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 - Initial release 1.0.1 - Improved error handling #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$Path, [Parameter(Mandatory = $true)] [string]$ChildPath ) try { Write-Verbose "Joining path '$Path' with child path '$ChildPath'" # 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 return $fullPath } catch { Write-Error "An error occurred: $_" } } |