Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created February 24, 2016 05:30
Show Gist options
  • Save Jaykul/726194b2419406ae35f6 to your computer and use it in GitHub Desktop.
Save Jaykul/726194b2419406ae35f6 to your computer and use it in GitHub Desktop.
A Format-Wide that can pivot the output and order it vertically
function Format-Wide {
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=113304')]
param(
[Parameter(Position=0)]
[System.Object]
${Property},
[switch]
${AutoSize},
[ValidateRange(1, 2147483647)]
[int]
${Column},
[System.Object]
${GroupBy},
[string]
${View},
[switch]
${ShowError},
[switch]
${DisplayError},
[switch]
${Force},
[ValidateSet('CoreOnly','EnumOnly','Both')]
[string]
${Expand},
[Parameter(ValueFromPipeline=$true)]
[psobject]
${InputObject},
# Flip the order of the output so it's ordered by columns instead of rows
[switch][Alias("Pivot")]
$OrderVertically
)
begin
{
function pivot-wide {
#.Synopsis
# Pivot the output of Format-Wide
#.Example
# Get-Verb | Sort Verb | Format-Wide -Auto | Pivot-Wide
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true)]
$InputObject
)
begin { $cache = @() }
process {
switch($InputObject.GetType().Name) {
"FormatStartData" { $columns = $InputObject.shapeInfo.columns; $InputObject }
"FormatEntryData" { $cache += $InputObject }
"GroupEndData" {
$count = $cache.Count
if($columns -eq 0) {
$width = ($cache | % {$_.formatEntryInfo.formatPropertyField.propertyvalue.length} | measure -Maximum).Maximum + 1
$cols = [Math]::Floor( $Host.UI.RawUI.BufferSize.Width / $width )
} else {
$cols = $columns
}
$rows = [Math]::Ceiling( $count / $cols )
Write-Verbose "$count items in $cols columns means $rows rows, with a max width of $width"
for($r=0; $r -lt $rows; $r++){
for($c=0; $c -lt $cols; $c++) {
$i = ($rows * $c) + $r
if($i -lt $count) {
Write-Verbose "Cell ($i)"
$cache[$i]
} else {
Write-Verbose "Blank ($i)"
$cache[0].formatEntryInfo.formatPropertyField.propertyvalue = ""
$cache[0]
}
}
}
$cache = @()
$InputObject
}
default { $InputObject }
}
}
}
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\Format-Wide', [System.Management.Automation.CommandTypes]::Cmdlet)
if($OrderVertically) {
$scriptCmd = {& $wrappedCmd @PSBoundParameters | pivot}
} else {
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
}
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Microsoft.PowerShell.Utility\Format-Wide
.ForwardHelpCategory Cmdlet
#>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment