如何在PowerShell中将Foreach循环嵌入到Html中

3wabscal  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(129)

我正尝试在PowerShell ISE中创建一个HTML循环,如下所示:

{foreach $obj in $objects}
   <h1>$obj.Name<h1>
{/foreach}

但它只打印对象列表中的最后一个。你做了什么?

qv7cva1a

qv7cva1a1#

使用expandable(内插)here-字符串,并通过子表达式运算符$(...)嵌入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()根据当时的变量值按需展开:


# 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>

注:

  • 考虑到$ExecutionContext.InvokeCommand.ExpandString()有点晦涩难懂,最好能有一个cmdlet来提供与GitHub issue #11693中建议的相同功能,比如命名为Expand-StringExpand-Template

相关问题