Question:
I have Windows 7 and PowerShell 4.0. When exporting content to a file the -Width
parameter does not format based on the given setting. Here is a sample of what I am trying to do:
1 2 |
"It is a nice hot sunny day" | Out-File -FilePath ".\output.txt" -Encoding ASCII -Width 10 |
The result of the export is not truncated at 10th character. It does not get truncated at all. I cannot figure out what’s wrong.
Answer:
This came as somewhat of a surprise to me, but apparently, the -Width
parameter only works with formatted objects:
String(s) as input, no effect
1 2 3 |
PS C:\> "It is a nice hot sunny day" |Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt' It is a nice hot sunny day |
Format-Table
, this works
1 2 3 4 5 6 |
PS C:\> New-Object psobject -Property @{text="It is a nice hot sunny day"} | Format-Table |Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt' text ----- It is a... |
Format-List
, this works, but in a strange manner:
1 2 3 4 5 6 7 8 9 10 11 12 |
PS C:\> New-Object psobject -Property @{text="It is a nice hot sunny day"} | Format-Table |Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt' text : It is a n ice ho t s unn y day |
So, the closest we can get is propably with Format-Table -HideTableHeaders
:
1 2 3 4 |
PS D:\> New-Object psobject -Property @{text="It is a nice hot sunny day"} | Format-Table -HideTableHeaders|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt' It is a... |
Inspired by @Matt’s answer, you could write your own function to truncate strings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Function Resize-String { Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]]$InputObject, [int]$Width = 10 ) process{ $InputObject.Substring(0,[System.Math]::Min([string]$InputObject[0].Length,$Width)) } } PS C:\> "It is a nice hot sunny day" |Resize-String|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt' It is a ni |