您正在寻找字符串模板,即根据占位符(变量)表示的当前值,按需扩展带有占位符的字符串的能力。
PowerShell 通过(鲜为人知)提供了这样的功能.InvokeCommand.ExpandString()的方法自动的$ExecutionContext多变的,它处理字符串值就好像它是 an 可展开(双引号)字符串 ("..."),即执行对其进行字符串插值:
- 通过以下方式保存您的 HTML 模板字符串verbatim细绳 ('...'),即一个single- 引用一,以防止instant嵌入变量引用的扩展,例如
$computer
:
# Note the use of *single* quotes, to ensure
# that $computername and $username *aren't* expanded.
@'
<!doctype html>
<html lang="en">
<head>
<body>
text
$computername
$username
text
</body>
</html>
'@ | Out-File c:\scripts\temp\Report.html
# Read the template in full (-Raw)
$htmlTemplate = Get-Content -Raw c:\scripts\temp\Report.html
# Perform sample instantiations of the template.
1..2 | ForEach-Object {
# Set the variable values to use in the template.
$computername = "computer$_"
$username = "user$_"
# Now instantiate the template
$ExecutionContext.InvokeCommand.ExpandString($htmlTemplate)
"---`n"
}
这会输出以下内容 - 请注意如何$computer
and $username
扩展到这些变量当时的值:
<!doctype html>
<html lang="en">
<head>
<body>
text
computer1
user1
text
</body>
</html>
---
<!doctype html>
<html lang="en">
<head>
<body>
text
computer2
user2
text
</body>
</html>
---
Caveat:
防止子表达式的扩展 ($(...)
),防止代码注入:
-
以下变体确保任何(未转义)$(...)
序列是exempt从扩展,即它们是逐字保留.
-
这是通过以下方式实现的`
- 逃离$
在每一个$(
顺序,但是仅当那样$
还没有逃脱。后一个要求需要不平凡的regex以下。简而言之,$
in $(
仅当其前面有以下任一情况时才必须转义no or an 偶数 of `
字符。 (后者形成一个序列转义转义字符,这意味着以下$
is 未逃脱的)。有关正则表达式的说明以及对其进行实验的选项,请参阅此 regex101.com 页面.
# Read the template in full (-Raw) and escape the $ of unescaped
# $( sequences with ` (backtick), which will prevent expansion of any
# $(...) subexpressions.
$htmlTemplate =
(Get-Content -Raw t.html) -replace '(?<!`)((?:``)*)\$\(', '$1`$$('
# Perform sample instantiations of the template.
1..2 | ForEach-Object {
# Set the variable values to use in the template.
$computername = "computer$_"
$username = "user2"
# Now instantiate the template.
$ExecutionContext.InvokeCommand.ExpandString($htmlTemplate)
"---`n"
}