我正尝试在PowerShell ISE中创建一个HTML循环,如下所示:
{foreach $obj in $objects} <h1>$obj.Name<h1> {/foreach}
但它只打印对象列表中的最后一个。你做了什么?
qv7cva1a1#
使用expandable(内插)here-字符串,并通过子表达式运算符$(...)嵌入foreach语句:
$(...)
foreach
# Sample objects. $objects = [pscustomobject] @{ name = 'foo1' }, [pscustomobject] @{ name = 'foo2' } # Use an expandable (double-quoted) here-string to construct the HTML. # The embedded $(...) subexpressions are *instantly* expanded. @" <html> $( $( foreach ($obj in $objects) { " <h1>$($obj.Name)<h1>" } ) -join "`n" ) </html> "@
产出:
<html> <h1>foo1<h1> <h1>foo2<h1> </html>
如果您希望将上述字符串定义为模板,以便可以重复、按需展开(字符串内插),则使用逐字here-字符串,并通过$ExecutionContext.InvokeCommand.ExpandString()根据当时的变量值按需展开:
$ExecutionContext.InvokeCommand.ExpandString()
# Use a verbatim (single-quoted) here-string as a *template*: # Note the @' / @' instead of @" / @" $template = @' <html> $( $( foreach ($obj in $objects) { " <h1>$($obj.Name)<h1>" } ) -join "`n" ) </html> '@ # Sample objects. $objects = [pscustomobject] @{ name = 'foo1' }, [pscustomobject] @{ name = 'foo2' } # Expand the template now. $ExecutionContext.InvokeCommand.ExpandString($template) '---' # Define different sample objects. $objects = [pscustomobject] @{ name = 'bar1' }, [pscustomobject] @{ name = 'bar2' } # Expand the template again, using the new $objects objects. $ExecutionContext.InvokeCommand.ExpandString($template)
<html> <h1>foo1<h1> <h1>foo2<h1> </html> --- <html> <h1>bar1<h1> <h1>bar2<h1> </html>
注:
Expand-String
Expand-Template
1条答案
按热度按时间qv7cva1a1#
使用expandable(内插)here-字符串,并通过子表达式运算符
$(...)
嵌入foreach
语句:产出:
如果您希望将上述字符串定义为模板,以便可以重复、按需展开(字符串内插),则使用逐字here-字符串,并通过
$ExecutionContext.InvokeCommand.ExpandString()
根据当时的变量值按需展开:产出:
注:
$ExecutionContext.InvokeCommand.ExpandString()
有点晦涩难懂,最好能有一个cmdlet来提供与GitHub issue #11693中建议的相同功能,比如命名为Expand-String
或Expand-Template
。