Skip to content

Instantly share code, notes, and snippets.

@trackd
Forked from indented-automation/ConvertTo-TableFormat.ps1
Last active January 14, 2024 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trackd/6cba343518c2fa7f4b13b8508a1e4812 to your computer and use it in GitHub Desktop.
Save trackd/6cba343518c2fa7f4b13b8508a1e4812 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
)
process {
if (-Not $Initial) {
$Initial = $true
$formatData = Get-FormatData -TypeName $InputObject[0].PSTypeNames |
Select-Object -First 1
if ($formatData) {
$viewDefinition = $formatData.FormatViewDefinition |
Where-Object Control -Match 'TableControl' |
Select-Object -First 1
$format = 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