Exploring the Out-String Cmdlet in PowerShell
Welcome back to Wahmans PowerShell Blog! Today, we’re going to dive into a very handy cmdlet: Out-String. As per Microsoft’s documentation, Out-String outputs input objects as a single string. This might sound simple, but it has some very powerful uses, especially when you need to manipulate or transform output in your scripts.
What Does Out-String Do?
The Out-String cmdlet collects the output of a command and converts it into a single string. Normally, when you output something in PowerShell, it goes to the console as individual objects. But sometimes, you need that output stored or processed as one big string—Out-String makes that easy.
Example 1: Basic Use
The simplest way to use Out-String is to convert something like a list of files into a single string:
$fileList = Get-ChildItem | Out-String
Write-Output $fileList
This will store the list of files and folders in the current directory into a single string variable, $fileList, which you can then manipulate or output elsewhere.
Example 2: Capturing Command Output
If you’re capturing the output of a command in string format to write to a file or pass into another command (like an email body), Out-String is your friend:
$serviceInfo = Get-Service | Where-Object {$_.Status -eq 'Running'} | Out-String
Set-Content -Path ".\RunningServices.txt" -Value $serviceInfo
This will filter running services and output their info into a formatted string that gets written to a text file.
Example 3: Working with Format Cmdlets
When you use cmdlets like Format-Table or Format-List, their output is formatting instructions, not actual string content. To capture that formatted output as a string, use Out-String:
$userInfo = Get-Process | Select-Object Name, Id, CPU | Format-Table -AutoSize | Out-String
Write-Output $userInfo
Here, without Out-String, the formatted table won’t be treated as text, which limits where you can send it.
Example 4: Checking Output Before Sending Email (Advanced)
Let’s say you want to send an email with the output of a command. Instead of piping command output directly, you want to control it as a string—perhaps to inspect or format it differently. Here’s how:
$report = Get-EventLog -LogName System -Newest 10 | Format-List | Out-String
if ($report.Length -gt 0) {
Send-MailMessage -To "[email protected]" -From "[email protected]" -Subject "Latest System Log Entries" \
-Body $report -SmtpServer "smtp.example.com"
}
In this example, we grab the latest system log entries, format them, convert to string, and send them via email if there’s content to send.
Wrapping Up
Out-String is a small but mighty cmdlet that can help you bridge the gap between object-oriented PowerShell output and scenarios where you need plain strings. Whether you’re writing to files, sending messages, or preparing formatted reports, Out-String keeps things consistent and script-friendly.
Happy scripting, and I will see you in the next post!
Leave a Reply