Expanding variables in file contents

Viewed 10761

I have a file template.txt which contains the following:

Hello ${something}

I would like to create a PowerShell script that reads the file and expands the variables in the template, i.e.

$something = "World"
$template = Get-Content template.txt
# replace $something in template file with current value
# of variable in script -> get Hello World

How could I do this?

3 Answers

Since I really don't like the idea of One More Thing To Remember - in this case, remembering that PS will evaluate variables and run any commands included in the template - I found another way to do this.

Instead of variables in template file, make up your own tokens - if you're not processing HTML, you can use e.g. <variable>, like so:

Hello <something>

Basically use any token that will be unique.

Then in your PS script, use:

$something = "World"
$template = Get-Content template.txt -Raw
# replace <something> in template file with current value
# of variable in script -> get Hello World    
$template=$template.Replace("<something>",$something)

It's more cumbersome than straight-up InvokeCommand, but it's clearer than setting up limited execution environment just to avoid a security risk when processing simple template. YMMV depending on requirements :-)

Related