Html部分
$html = @($htm)
$html = @"
<!doctype html>
<html lang="en">
<head>
<body>
text
$computername
$username
text
</body>
</html>
"@
$html | out-file c:\scripts\temp\Report.html
我在 $html 变量中有 html 语言。当我决定更改 HTML 代码时,我需要返回 PowerShell 脚本。我宁愿将 html 放在单独的文件中。如何使用 get-content 将单独文件的内容放入 $html = @"..."@
变量中。
我在 html 部分使用 powershell $variables 来制作动态电子邮件!
最佳答案
您正在寻找字符串模板,即根据占位符(变量)表示的当前值,按需扩展带有占位符的字符串的能力。
PowerShell 通过(鲜为人知的).InvokeCommand.ExpandString()
提供了这样的功能。 automatic $ExecutionContext
variable的方法,它将字符串值视为 expandable (double-quoted) string ("..."
) ,即对其执行字符串插值:
- 通过 verbatim string (
'...'
) 保存您的 HTML 模板字符串,即单引用,以防止即时扩展嵌入式变量引用,例如$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
和 $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>
---
警告:
上面假设您完全控制或隐式信任 HTML 模板文件的内容,因为可以注入(inject)任意命令到模板中,使用
$(...)
,subexpression operator请参阅下文,了解防止子表达式扩展的方法。
防止子表达式的扩展($(...)
),以防止代码注入(inject):
以下变体可确保任何(未转义的)
$(...)
序列免除扩展,即它们逐字保留.这是通过在每个
$(
序列中转义$
来实现的,但仅当$
尚未转义。后一个要求需要下面重要的 regex。简而言之,$( 中的
前面有 no 或偶数$
仅当`
字符时才必须进行转义。(后者形成序列转义转义字符,这意味着以下$
是未转义)。有关正则表达式和实验选项的说明,请参阅this regex101.com page。
# 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"
}
关于html - 将 get-content 放入 html 电子邮件的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77221990/