Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active December 12, 2023 08:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save indented-automation/834284b6c904339b0454199b4745237e to your computer and use it in GitHub Desktop.
Save indented-automation/834284b6c904339b0454199b4745237e to your computer and use it in GitHub Desktop.
function ConvertTo-TableFormat {
<#
.SYNOPSIS
Rebuild an object based on the Format Data for the object.
.DESCRIPTION
Allows an object to be rebuilt based on the view data for the object. Uses Select-Object to create a new PSCustomObject.
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[Object]$InputObject
)
begin {
$isFirst = $true
}
process {
$format = if ($isFirst) {
$formatData = Get-FormatData -TypeName $InputObject[0].PSTypeNames |
Select-Object -First 1
if ($formatData) {
$viewDefinition = $formatData.FormatViewDefinition |
Where-Object Control -match 'TableControl'
for ($i = 0; $i -lt $viewDefinition.Control.Headers.Count; $i++) {
$name = $viewDefinition.Control.Headers[$i].Label
$displayEntry = $viewDefinition.Control.Rows.Columns[$i].DisplayEntry
if (-not $name) {
$name = $displayEntry.Value
}
$expression = switch ($displayEntry.ValueType) {
'Property' { $displayEntry.Value }
'ScriptBlock' { [ScriptBlock]::Create($displayEntry.Value) }
}
@{ Name = $name; Expression = $expression }
}
}
}
if ($format) {
$InputObject | Select-Object -Property $format
} else {
$InputObject
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment