Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell templating

Tags:

powershell

I've got an app config file that contains two types of templated variables. The first set will be populated at build time by some powershell scripts. The second remain within the config file but are used at runtime.

So, under source control, the file might look like:

<property name="$($settings.elementName)" value="${valueThatIsSubstitutedAtRuntime}" />

After a build I'd like it to be:

<property name="settingFromPosh" value="${valueThatIsSubstitutedAtRuntime}" />

But unfortunately it's coming out as

<property name="settingFromPosh" value="" />

I'm using the a slightly modified version of the templating method described in Powershell for Developers. Basically, I'm using populating a ScriptBlock with the variables to substitute, reading the template and calling Invoke-Expression with the template content. The script it successfully substituting values it can find but also wiping out any it can't.

I'm reluctant to use regex token replacements because I want the full power of ps within the template. Also, I prefer not to introduce different variable tokens for the values I don't want populated during the build.

Is there a way to leave variables in place that can't be substituted or perhaps escape them so they're ignore?

like image 314
Joe Avatar asked Jan 17 '26 17:01

Joe


1 Answers

Put your string in single-quotes so that PowerShell doesn't try to expand any variables in it e.g.:

<property name="$($settings.elementName)" value='${valueThatIsSubstitutedAtRuntime}' />

Then you can use $ExecutionContext.InvokeCommand.ExpandString(...) to expand the string at runtime e.g.:

$foo = 'bar'
$str = '$foo'
$ExecutionContext.InvokeCommand.ExpandString($str)
like image 157
Keith Hill Avatar answered Jan 20 '26 13:01

Keith Hill