Search code examples
powershellvariablesstring-interpolation

How does one replace a variable in a string with its value?


I see lots of examples of using variables in strings but this is a slightly different problem and maybe I am not phrasing it correctly in order to search for an answer. I have a string that has a variable in it, but the variable's value has not been replaced with the value. I am storing this string in a database so the settings can be changed without code changes and so that several scripts can share these values.

If I type this into the shell:

$ScriptPath = "C:\Scripts"
$LogPath = "$ScriptPath\Logs"

It works perfectly. I get back C:\Scripts\Logs

If I read that string from a database, it is a different story.

$SQL = "SELECT * FROM Script_Settings WHERE enabled = 1 AND (environment = '$Environment' OR environment = '*') AND version = $Version ORDER BY environment"
$sqlresult = Invoke-SQLCmd -ServerInstance $SettingDBServer -Database $SettingsDB -Query $SQL -TrustServerCertificate
$LogPath = $sqlresult.Log_Path
Write-Output $LogPath

$ScriptPath\Logs

Is it possible to get Powershell to evaluate the string? I suppose it is the equivalent of:

$ThePath = '$ScriptPath\Logs'
$LogPath = $ThePath

Solution

  • A quick way to use string templates in PowerShell is to invoke $ExecutionContext.InvokeCommand.ExpandString to interpolate strings.

    $ScriptPath = "C:"
    $ThePath = '$ScriptPath\Logs'
    $ExecutionContext.InvokeCommand.ExpandString($ThePath)
    

    Will return

    C:\Logs