Html portion
$html = @($htm)
$html = @"
<!doctype html>
<html lang="en">
<head>
<body>
text
$computername
$username
text
</body>
</html>
"@
$html | out-file c:scriptstempReport.html
I have html language in the $html variable. When I decide to change the HTML code I need to go back into the PowerShell script. I’d rather just have the html in a separate file. How can I use get-content to place the contents of separate file into the $html = @"..."@
variable.
I am using powershell $variables in the html portion to make dynamic emails!
3
Answers
Dependent on your use case, a simple string replacement might work:
If you need to have a HTML template where several variables need to be inserted, I would rather use a structured CSV file than a simple text file to read the variable values needed.
Lets say your csv file looks like this:
Option 1: Use a HTML template with numeric placeholders to use with the
-f
Format operatorThen use like
Option 2: Use a HTML template with string placeholders to use with
.Replace()
or-replace
Note:
Instead of the string
.Replace()
method you could also use-replace
or-creplace
regex operators likewhere
-replace
is a case-insensitive operator. If you need it to work case-sensitively, then use-creplace
When you need to insert many variables, option 1 would be my preferred way..
You’re looking for string templating, i.e. the ability to expand a string with placeholders on demand, based on the then-current values that the placeholders (variables) represent.
PowerShell offers such a feature via the (little-known)
.InvokeCommand.ExpandString()
method of the automatic$ExecutionContext
variable:'...'
), i.e., a single-quoted one, so as to prevent instant expansion of embedded variable references such as$computer
:This outputs the following – note how
$computer
and$username
were expanded to the then-current values of these variables:Caveat:
$(...)
, the subexpression operator