Reputation: 333
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?
Upvotes: 3
Views: 2051
Reputation: 201922
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)
Upvotes: 1
Reputation: 68331
Are you sure this:
"${valueThatIsSubstitutedAtRuntime}"
shouldn't be:
&{valueThatIsSubstitutedAtRuntime}
That first one is the syntax for a braced variable. I think it's looking for a variable named "whatever is between the braces" (and not finding it, so it returns a null string). If it's a script block, I'd think you'd want to invoke it.
Upvotes: 0