Try the following:
$servers= 'GT544', 'HT54765', 'J4356', 'SW5654', 'JY67432'
$servers | ConvertTo-Html -Property @{ l='Name'; e={ $_ } }
Note: As EBGreen observes, the $servers
variable shouldn't be type-constrained as [string] $servers = ...
, because that converts the array of strings to a single string. There is no strict need to type-constrain in this case, but you could use [string[]] $servers = ...
ConvertTo-Html
by default enumerates all properties of the input objects, and in the case of [string]
instances that is only the .Length
property.
Therefore you need to use a calculated property that wraps your strings, which is what
@{ l='Name'; e={ $_ } }
does; the l
entry gives your property a name (will be used in the table header), and e
entry defines its value via a script block ({ ... }
), which in this case is simply the input string itself ($_
).
For more on calculated properties, see this answer of mine, but note that ConvertTo-Html
curiously only supports the l
/ label
key for naming the property (not also n
/ name
).
Also, passing calculated properties is currently broken altogether in PowerShell Core, as of v6.1.0-preview.2
The above yields:
<!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>
To put it all together:
$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