Question:
I have a cmdlet that uses Format-Table
to output potentially long strings (such as registry paths). I would like to set each column width to the output buffer width divided by the number of columns.
Example:
1 2 3 4 5 6 7 8 9 |
function Write-Something { [CmdletBinding()] param() $o = [pscustomobject]@{ a = 'A' * 100; b = 'B' * 100 } $columnWidth = [int]( $PSCmdlet.Host.UI.RawUI.BufferSize.Width / 2 ) $o | Format-Table @{ e = 'a'; width = $columnWidth }, @{ e = 'b'; width = $columnWidth } -wrap } |
This works nicely for console output, where it produces output like this:
1 2 3 4 5 |
a b - - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAA BBBBBBBBBBBB |
Problem
When I specify a different output buffer width, using the Width
argument of Out-String
or Out-File
, the formatting won’t change, it will still be based on the console buffer width.
1 2 |
Write-Something | Out-File test.txt -Width 200 |
This produces the same output as above whereas the expected output should be columns of width 100, with no wrapping occuring.
How can I get the actual output buffer width set by the Width
argument of Out-String
or Out-File
from within my cmdlet?
Answer:
The problem is that you’ve already fixed the width in your Write-Something cmdlet. The PowerShell way to do this would be for your cmdlet to output your unformatted data objects and for you to replace Out-File with your own cmdlet which controls the output width.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function Write-Something { [CmdletBinding()] param() $o = [pscustomobject]@{ a = 'A' * 100; b = 'B' * 100 } Write-Output $o } function Out-Something { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [psobject]$InputObject, [Parameter(Position=1)] [String]$FilePath, [Parameter(Position=2)] [int]$Width ) $columnWidth = [int]( $Width / 2 ) $InputObject | Format-Table @{ e = 'a'; width = $columnWidth }, @{ e = 'b'; width = $columnWidth } -Wrap | ` Out-File -FilePath $FilePath -Width $Width } Write-Something | Out-Something test.txt -Width 200 |