CmdLets/Master/Convert-PlaceholderVariables.ps1
|
Function Convert-PlaceholderVariables { <# .SYNOPSIS Replaces bracketed placeholder tokens in a string with actual variable values from the session. .DESCRIPTION The Convert-PlaceholderVariables function scans a target string for placeholder patterns formatted as [VariableName]. It iterates through a specified collection of variables (defaulting to $Global:Variables), verifies their existence, and replaces each placeholder with the corresponding variable's current value. .PARAMETER Value The input string containing bracketed placeholders to be evaluated and replaced (e.g., "Hello [UserName]"). .PARAMETER Variables An optional collection or array of variable objects to check for substitutions. Each object should contain at least a 'Name' property. Defaults to `$Global:Variables`. .EXAMPLE $Global:Variables = @([PSCustomObject]@{ Name = "Env"; Value = "Production" }) Convert-PlaceholderVariables -Value "Target environment is [Env]." Description: Replaces the [Env] placeholder in the string with "Production". .NOTES Prerequisites: - Variables specified or referenced must exist in the session scope for successful substitution. .LINK https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-variable #> [CmdletBinding()] Param( [Parameter(Mandatory=$False)] [String]$Value, [Parameter(Mandatory=$False)] $Variables=$Global:Variables ) ForEach ($Variable in $Variables) { If (Get-Variable -Name $Variable.Name -ErrorAction SilentlyContinue) { $Variable = Get-Variable -Name $Variable.Name -ErrorAction SilentlyContinue $Value = $Value.Replace("[$($Variable.Name)]", $Variable.Value) } } Return $Value } |