Template templates

I have an application config file that contains two types of template variables. The first set will be populated at build time with some powershell scripts. The second remains in the config file, but is used at runtime.

So, when controlling the source, the file might look like this:

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

      

After assembly, I would like:

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

      

But unfortunately it looks like

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

      

I am using a slightly modified version of the templating method described in Powershell for Developers. Basically, I use ScriptBlock padding with replaceable variables, reading the template, and calling Invoke-Expression with the template content. script it successfully replaces the values ​​it can find, but also destroys anything it cannot.

I don't want to use regex token replacements because I need the full power of ps inside the template. Also, I prefer not to inject different variable tokens for values ​​that I don't want to be populated at build time.

Is there a way to leave variables in place that cannot be replaced, or perhaps avoid them so that they are ignored?

+3


source to share


2 answers


Place your string in single quotes so that PowerShell doesn't try to expand any variables in it, for example:

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

      



Then you can use $ExecutionContext.InvokeCommand.ExpandString(...)

to expand the string at runtime like:

$foo = 'bar'
$str = '$foo'
$ExecutionContext.InvokeCommand.ExpandString($str)

      

+1


source


You are sure that:

"${valueThatIsSubstitutedAtRuntime}" 

      

must not be:



&{valueThatIsSubstitutedAtRuntime} 

      

This is the first syntax for a parenthesis variable. I think it is looking for a variable named "whatever is between the curly braces" (and doesn't find it, so it returns an empty string). If it's a script block, I think you would like to call it.

0


source







All Articles