Search code examples
powershellformattingpowershell-2.0

How do I use Format-Table without truncation of values?


I currently have a script that pings servers and checks the status of services running on each server.

I save the output with Out-File but PowerShell places ellipses or "..." after long strings. I don't want it to do this. For example:

MachineName  ServiceName             Status StartType
-----------  -----------             ------ ---------
SrvGtw01     Test.MyService....       Running  

I want it to display the full name like:

MachineName  ServiceName              Status StartType
-----------  -----------              ------ ---------
SrvGtw01     Test.MyServiceName.Here  Stopped  Disabled

I've been reading that you can set the $FormatEnumerationLimit preference variable to -1 and I have tried that but it's not working. I'm not sure how I should place it in my script.


Solution

  • The $FormatEnumerationLimit preference variable doesn't apply here, because its purpose is to determine how many elements of a collection-valued property to display (e.g, $FormatEnumerationLimit = 2; [pscustomobject] @{ prop = 1, 2, 3 } prints (at most) 2 elements from .prop's value and hints at the existence of more with ...; e.g., {1, 2...}).

    Instead, you must:

    • (a) ensure that individual columns don't truncate their values on display:

      • Pipe to Format-Table -Autosize first.
    • and (b) ensure that the overall output width can fit all columns:

      • Pipe to Out-File -Width with a sufficiently large value (don't use [int]::MaxValue, though, because every line of tabular output gets padded to that very width[1]) .

        • Caveat: If you don't set -Width explicitly - as would happen if you just used >, for instance - the current console window's width is used - whatever it happens to be.

    For instance:

    # Assumes that the objects in $results only contain the properties
    # of interest (MachineName, ServiceName, Status, StartType); you 
    # can also pass an explicit list of output properties to Format-Table, however.
    $results | Format-Table -AutoSize | Out-File -Width 512 C:\log.txt -Append
    

    Note: To preview the output in the console - which may involve line-wrapping - use
    Out-String -Width 512 instead.


    [1] In PowerShell (Core) 7+ this undesirable last-column padding has been removed.