Out String - PowerShell


Overview

Out-String is a PowerShell cmdlet for converting input into a string. It takes various input types, including objects, arrays, collections, and strings, and transforms them into a single consolidated string.

Syntax

Out-String [-InputObject] <Object | Array | Collection> [-Stream] [-Width <Int32>] [-Culture <String>] [-OutVariable]

Options/Flags

  • -InputObject: Specifies the input to be converted into a string. Accepts pipeline input or direct object values.
  • -Stream: Converts the input into a continuous string stream, removing line breaks and other formatting.
  • -Width: Sets the maximum line width for the output string. Default value: Window width.
  • -Culture: Specifies the culture for formatting numbers and dates in the output string. Default value: Invariant culture.
  • -OutVariable: Stores the result in a specified variable for further use.

Examples

Outputting a Simple Object:

$person = Get-ChildItem C:\Users\Admin
Out-String -InputObject $person

Converting an Array to a String:

$numbers = 1, 2, 3, 4, 5
$str = Out-String -Stream -InputObject $numbers

Controlling Output Width:

Out-String -Width 60 -InputObject (Get-Date)

Common Issues

  • Unexpected Line Breaks: By default, Out-String preserves line breaks. Use the -Stream parameter to suppress line breaks.
  • Non-String Output: If the input is not a string, it may not be displayed correctly. Consider using ConvertTo-Json or ConvertTo-Xml before piping to Out-String.

Integration

Use with Format-Table:

Get-Process | Format-Table -AutoSize | Out-String

Pass to Write-Host:

$output = Out-String -InputObject $data
Write-Host $output