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:
"ComputerName","UserName"
"PC0123","Roger Rabbit"
"PC8769","Daffy Duck"
"PC5544","Yosemite Sam"
Option 1: Use a HTML template with numeric placeholders to use with the -f
Format operator
$html = @"
<!doctype html>
<html lang="en">
<head>
<body>
text
{0}
{1}
text
</body>
</html>
"@
Then use like
Import-Csv -Path 'X:\Somewhere\UsersAndComputers.csv' | ForEach-Object {
# replace the placeholder strings {0} and {1} etc. with values from the csv
$newHtml = $html -f $_.ComputerName, $_.UserName
# create a path and filename for the filled-in html
$newFile = 'C:\scripts\temp\Report_{0}.html' -f $_.UserName
# write the file
$newHtml | Set-Content -Path $newFile -Encoding UTF8
}
Option 2: Use a HTML template with string placeholders to use with .Replace()
or -replace
$html = @"
<!doctype html>
<html lang="en">
<head>
<body>
text
@@COMPUTERNAME@@
@@USERNAME@@
text
</body>
</html>
"@
Import-Csv -Path 'X:\Somewhere\UsersAndComputers.csv' | ForEach-Object {
# replace the placeholder strings with values from the csv
$newHtml = $html.Replace('@@COMPUTERNAME@@', $_.ComputerName).Replace('@@USERNAME@@', $_.UserName)
# create a path and filename for the filled-in html
$newFile = 'C:\scripts\temp\Report_{0}.html' -f $_.UserName
# write the file
$newHtml | Set-Content -Path $newFile -Encoding UTF8
}
Note:
Instead of the string .Replace()
method you could also use -replace
or -creplace
regex operators like
$newHtml = $html -replace '@@COMPUTERNAME@@', $_.ComputerName -replace '@@USERNAME@@', $_.UserName
where -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..
if ($htmlTemplate -match "\$\(.+\)") {throw "This template contains possible arbitrary code"}
right after reading the template. Obsiously, this cannot be done if your template needs such code... – Calvaria