Powershell 通过管道将字符串数组传递给 ConvertTo-Html

Powershell piping an array of strings to ConvertTo-Html

出于测试目的(在我申请我的大代码之前)我决定将一个字符串数组通过管道传递给 convertTo-html 希望创建某种 table 来显示我的数组。

[String]$servers= @('GT544', 'HT54765', 'J4356', 'SW5654', 'JY67432')
psedit "C:\Users\karljoey.chami\Desktop\Htmltesting\Red.css"
$file = "C:\Users\karljoey.chami\Desktop\Htmltesting\Result.html"
$servers | ConvertTo-Html 
-Title "Servers in a table" -CssUri "C:\Users\karljoey.chami\Desktop\Htmltesting\Red.css" 
-pre "<h>The servers are</h>" | Out-file $file 
Invoke-Item $file

问题是我的字符串数组被传输为数组包含的字符数而不是元素本身。

尝试以下操作:

$servers= 'GT544', 'HT54765', 'J4356', 'SW5654', 'JY67432'
$servers | ConvertTo-Html -Property @{ l='Name'; e={ $_ } }

注意:正如 EBGreen 观察到的,$servers 变量不应该像 [string] $servers = ... 那样是 type-constrained,因为那样会转换字符串数组到 单个 字符串。在这种情况下没有严格需要 type-constrain,但您可以使用 [string[]] $servers = ...

ConvertTo-Html 默认枚举输入 objects 的所有 属性 ,在 [string] 实例的情况下,只有 .Length 属性.

因此您需要使用计算的属性包装您的字符串,这就是
@{ l='Name'; e={ $_ } } 确实如此; l 条目为您的 属性 提供了一个 名称 (将在 table header 中使用),以及 e条目通过脚本块 ({ ... }) 定义其 value,在本例中它只是输入字符串本身 ($_).

有关计算属性的更多信息,请参阅我的 this answer,但请注意 ConvertTo-Html 奇怪地只支持 l / label 键命名 属性(不是 n / name)。
此外,传递计算属性是 currently broken altogether in PowerShell Core, as of v6.1.0-preview.2

以上结果:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/></colgroup>
<tr><th>Name</th></tr>
<tr><td>GT544</td></tr>
<tr><td>HT54765</td></tr>
<tr><td>J4356</td></tr>
<tr><td>SW5654</td></tr>
<tr><td>JY67432</td></tr>
</table>
</body></html>

将它们放在一起:

$servers = 'GT544', 'HT54765', 'J4356', 'SW5654', 'JY67432'
$file = "C:\Users\karljoey.chami\Desktop\Htmltesting\Result.html"

$servers | ConvertTo-Html -Property @{ l='Name'; e={ $_ } } -Title "Servers in a table" `
  -CssUri "C:\Users\karljoey.chami\Desktop\Htmltesting\Red.css" `
  -pre "<h>The servers are</h>" | Out-file $file  

Invoke-Item $file