Exploring the PowerShell Cmdlet: Join-String
Welcome back to Wahman’s PowerShell Blog! Today, we are diving into the Join-String cmdlet — a powerful and flexible tool introduced in PowerShell 7. This cmdlet does exactly what its name suggests: it combines objects from the pipeline into a single string!
Whether you’re a beginner just learning about PowerShell pipeline principles or a power user looking to format output in unique ways, Join-String can be an invaluable tool in your scripting toolbox.
Cmdlet Description
According to Microsoft’s documentation, Join-String “combines objects from the pipeline into a single string.” You can customize formatting with parameters such as -Separator, -OutputPrefix, -OutputSuffix, and -Property.
Now, let’s look at some practical examples—from beginner-friendly to more advanced use cases.
Example 1: Joining Basic Strings – Beginner Level
"apple", "banana", "cherry" | Join-String -Separator ", "
Output:
apple, banana, cherry
This simple command takes a list of strings and joins them using a comma and space as the separator. Super useful for formatting text lists!
Example 2: Joining Object Properties – Intermediate Level
$users = @(
@{ Name = "Alice" },
@{ Name = "Bob" },
@{ Name = "Charlie" }
)
$users | Join-String -Property Name -Separator "; "
Output:
Alice; Bob; Charlie
Instead of just joining plain strings, we pull out the Name property from each object and join them. This is very helpful when working with data pulled from AD or APIs.
Example 3: Adding Prefixes and Suffixes – Advanced Formatting
1..3 | Join-String -OutputPrefix "[" -OutputSuffix "]" -Separator ", "
Output:
[1, 2, 3]
Want to format your string with brackets and commas? This technique is great for outputting data into custom formats, such as JSON-like arrays or CSV-friendly structures.
Example 4: Grouped Join with ScriptBlock Formatter – Advanced Level
$services = Get-Service | Select-Object -First 5
$services | Join-String -Property { "$($_.Name) ($($_.Status))" } -Separator " | "
Output: (example)
AdobeUpdateService (Running) | AppXSvc (Stopped) | BITS (Running) | CDPSvc (Running) | CryptSvc (Running)
In this example, we use a script block to craft complex output by combining multiple properties from the object. This is incredibly useful when you need customized output formatting, such as for reports or logs.
Wrap-Up
As you’ve seen, Join-String is a compact yet flexible cmdlet that makes it easy to combine and format strings and object properties right from the pipeline. Its simple syntax and powerful options make it a worthy addition to any PowerShell scripter’s toolkit.
Happy scripting, and I will see you in the next post!
Leave a Reply