Converting Text Arrays to String

by May 19, 2014

Occasionally, text from a text file needs to be read and processed by other commands. Typically, you would use Get-Content to read the text file content, then pass the result on to other commands. This may fail, though.

And here is the caveat: Always remember that Get-Content returns an array of text lines, not a single text line. So whenever a command expects a string rather that a bunch of text lines (a string array), you need to convert text lines to text.

Beginning in PowerShell 3.0, Get-Content has a new switch parameter called -Raw. It will not only speed up reading large text files but also return the original text file content in one chunk, without splitting it into text lines.

PS> $info = Get-Content $env:windir\windowsupdate.log
PS> $info -is [Array]
True

PS> $info = Get-Content $env:windir\windowsupdate.log -Raw
PS> $info -is [Array] 
False

If you already have text arrays and would like to convert them to a single text, use Out-String:

PS> $info = 'One', 'Two', 'Three'
PS> $info -is [Array]
True

PS> $all = $info | Out-String
PS> $all -is [Array]
False 

Twitter This Tip! ReTweet this Tip!