Home > database >  Powershell adjust the format table width
Powershell adjust the format table width

Time:05-07

This is the script

get-childitem D:\media\*.mkv -recurse | Select-Object -Property name,  @{n='Resolution';expression={mediainfo $_.FullName --inform="Video;%Width%x%Height%"}}

and the output is

Name                      Resolution
----                      ----------
Video File -Copy (2).mkv 1920x1080 
Video File -Copy (3).mkv 1920x1080 
Video File -Copy (4).mkv 1920x1080 
Video File -Copy (5).mkv 1920x1080 
Video File -Copy (6).mkv 1920x1080 
Video File -Copy (7).mkv 1920x1080 
Video File -Copy.mkv     1920x1080 
Video File.mkv           1920x1080 

but if file name character is big, the resolution column info get missing. name column info gets overlapping.

i read this page https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/format-table?view=powershell-7.2

but i am not sure how to implement the property width or auto size.

CodePudding user response:

You can use Format-Table with a calculated property to limit the width of the Name column; e.g.:

... | Format-Table @{ Name='Name'; Expression = 'Name'; Width = 60 }, Resolution

Longer values are then truncated with ... / in Windows PowerShell / PowerShell (Core) 7 . You may add -Wrap to show them in full, spread across as many lines as needed.

The alternative - which won't render nicely on screen - is to pipe to Out-String and use its -Width parameter with a terminal-column count large enough to accommodate all table columns:

... | Out-String -Width 300

Note: With your output objects, Format-Table formatting is implied (they have 4 or fewer properties), which is why there's no explicit call to it above.

As an aside:

  • Format-Table -Autosize does not help, as it doesn't ensure that all columns are shown - see this answer for more information.

Sample code:

[pscustomobject] @{
  Name = 'x' * 80   'y'
  Resolution = '1920x1080'
},
[pscustomobject] @{
  Name = 'x' * 280   'z'
  Resolution = '2560x1600'
} |
  Format-Table -Wrap @{ Name='Name'; Expression = 'Name'; Width = 60 }, Resolution

Output:

Name                                                         Resolution
----                                                         ----------
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 1920x1080
xxxxxxxxxxxxxxxxxxxxy
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 2560x1600
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz
  • Related