Quick template text file implementation in Powershell 1

If you write scripts, there are good chances you have some of them whose sole purpose is to duplicate configuration files or reports with data depending on variables.
A quick way to implement this in Powershell is to use the combined power of Here-Strings and expressions using variables.

The basic idea is to store the template as a text file, using variables and derived expressions to act as data placeholders :


Then we’ll have to figure out how to read that template file, let Powershell replace the variables and expressions by their contents, and do whatever we need.

If you simply read the contents of the file with Get-Content, the variables are not expanded, so you’ll have to figure out how to build an instruction, expression, or scriptblock that will make Powershell interpret it.

Since we are talking about expressions, let’s use Invoke-Expression. The only missing piece of the puzzle is how to transform that string (or array of strings) we read with Get-Content into a valid Powershell expression.

Here (!) come the Here-Strings by noticing that  the following code will build a valid here-string from any variable

If you have trouble reading that expression, remember that

  • the opening and ending tags of a here-string must be on their own line, hence the CR LF pairs;
  • the CR LF, and double-quote symbol must be written using the backtick as we are inside  double-quoted string.

Then our full solution will be:



Leave a comment

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “Quick template text file implementation in Powershell