How to use the command Out-String (with examples)
- Windows
- December 25, 2023
The Out-String command is used in PowerShell to output input objects as a string. It is a useful tool when you want to convert objects into a format that can be easily manipulated or displayed.
Use case 1: Print host information as string
Code:
Get-Alias | Out-String
Motivation:
In this use case, the Get-Alias command is executed to retrieve the list of all aliases in PowerShell. By piping the output to Out-String, the output is converted into a string format which can be printed or further manipulated.
Explanation:
Get-Alias
: Retrieves the list of all aliases in PowerShell.Out-String
: Converts the input objects (in this case, the list of aliases) into a string format.
Example output:
CommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
Alias ? -> Where-Object
Alias ac -> Add-Content
...
Use case 2: Convert each object to a string rather than concatenating all the objects into a single string
Code:
Get-Alias | Out-String -Stream
Motivation:
By default, when you use Out-String, all the input objects are concatenated into a single string. However, in some cases, you may want to have each object as a separate string. This is where the -Stream parameter comes in handy.
Explanation:
Get-Alias
: Retrieves the list of all aliases in PowerShell.Out-String
: Converts the input objects (in this case, the list of aliases) into a string format.-Stream
: Specifies that each input object should be converted into a separate string.
Example output:
CommandType Name Version Source
----------- ---- ------- ------
Alias %
Alias ?
Alias ac
...
Use case 3: Use the Width parameter to prevent truncation
Code:
@{TestKey = ('x' * 200)} | Out-String -Width 250
Motivation:
In some cases, when you have long strings or wide tables, the output may get truncated, making it difficult to read or use. The -Width parameter can be used to specify the width of the output, preventing truncation.
Explanation:
@{TestKey = ('x' * 200)}
: Creates a hashtable with a single key-value pair, where the value is a string of 200 ‘x’ characters.Out-String
: Converts the input object (the hashtable) into a string format.-Width
: Specifies the width of the output string.
Example output:
Name Value
---- -----
TestKey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Conclusion:
The Out-String command in PowerShell is a powerful tool for converting input objects into a string format, making them easier to manipulate or display. Whether you need to print host information, separate each object into individual strings, or prevent truncation, Out-String provides the necessary capabilities.