views:

202

answers:

2

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?

A: 

I've found this solution:

$something = "World"
$template = Get-Content template.txt
$expanded = Invoke-Expression "`"$template`""
$expanded
Paolo Tedesco
Could get you in trouble if there was code in the file.
Mike Shepard
+4  A: 

Another option (and safer) is to use ExpandString() e.g.:

$expanded = $ExecutionContext.InvokeCommand.ExpandString($template)

Invoke-Expression will execute any arbitrary code e.g.:

# Contents of file template.txt
"EvilString";$(remove-item -whatif c:\ -r -force -confirm:$false -ea 0)

$template = gc template.txt
iex $template # could result in a bad day
Keith Hill
That's perfect, thanks!
Paolo Tedesco