PowerShell新手求助:如何将无可用属性的Object数组转换为指定格式的HTML表格
Hey there! Let's work through this PowerShell formatting hurdle you're facing. I’ve dealt with similar confusing object array scenarios before, so I know how frustrating it is when you can see the data but can’t pull it out cleanly.
First off, the key issue here is likely that the displayed column names don’t match the actual property names of the objects in your $localAccounts array. Or maybe some property names have spaces (like "Is Group" or "Role Description") which need special handling in PowerShell.
Let’s break this down step by step:
1. First, confirm the real property names
Run this command to see exactly what properties each object in the array has:
$localAccounts | Get-Member -MemberType Property
This will list every accessible property name. You might find that the "Principal" column you see is actually stored under a property like PrincipalName, or that "Role Description" is RoleDesc—you never know until you check!
2. Transform the data to match your desired columns
Once you have the correct property names, use Select-Object to reshape the data. If the properties do match the displayed names (including those with spaces), use this syntax to rename and select the columns you want:
$transformedData = $localAccounts | Select-Object ` @{Name='UserName'; Expression={$_.Principal}}, # Rename "Principal" to "UserName" Role, @{Name='Description'; Expression={$_.'Role Description'}} # Handle space in property name
The @{Name='...'; Expression={...}} syntax lets you rename properties and pull values from existing ones.
3. Convert to HTML table
Now turn that transformed data into the HTML table you want:
# Use -Fragment if you only need the <table> element (no full HTML document) $htmlOutput = $transformedData | ConvertTo-Html -Property UserName, Role, Description -As Table -Fragment # If you want a complete HTML page, skip the -Fragment parameter # $htmlOutput = $transformedData | ConvertTo-Html -Property UserName, Role, Description -As Table # Save to a file or output to console $htmlOutput | Out-File -Path ".\UserRolesTable.html"
Why this works
PowerShell often shows friendly column names in the console, but those don’t always map directly to the object’s actual property names. Using Get-Member reveals the true names, and the calculated properties in Select-Object let you reshape the data exactly how you need it before converting to HTML.
Give this a shot—start with the Get-Member step to make sure you’re targeting the right properties, and adjust the Select-Object expression if needed.
内容的提问来源于stack exchange,提问作者Robert Bellarmin

