Background
While programming, occasionally there will be a need to have string contents that exceed a single line.
In this post, we will discuss some of the tools that Powershell offers.
Outline
- Here String
- String Concatenation Using Plus Sign
Options
Here String
Basic
Code
$strBuffer = @" Bob was here not too long ago "@ Write-Host $strBuffer
Output
Image
Text
>powershell success\string.hereString.ps1 Bob was here not too long ago
with whitespace before the beginning of the string
Code
$strBuffer = @" Bob was here not too long ago "@ Write-Host $strBuffer
Output
Image
Text
>powershell success\string.hereString.with.whiteSpace.before.stringBegining.ps1 Bob was here not too long ago
with whitespace before string terminator
Code
$strBuffer = @" Bob was here not too long ago "@ Write-Host $strBuffer
Output
Image
Text
At string.hereString.with.whiteSpace.before.stringTerminator.ps1:5 char:5 + "@ + ~~ White space is not allowed before the string terminator. + CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : WhitespaceBeforeHereStringFooter
Explanation
- Error Message
- White space is not allowed before the string terminator
String Concatenation Using Plus Sign
Use Plus Sign at the end of each string to be continued
Code
$strBuffer = "Bob was here " + "not too long ago" Write-Host $strBuffer
Output
Image
Text
>powershell success\string.plusSign.after.ps1 Bob was here not too long ago
Use Line Continuation at the end of each line that will be continued
Outline
- In this example, we will use the line continued indicator (`) to indicate that the current line is not yet complete
- And, that it will be continued on the next line
Code
$strBuffer = "Bob was here "` + "not too long ago" Write-Host $strBuffer
Output
Image
Text
>powershell success\string.plusSign.before.previousLineContinued.ps1 Bob was here not too long ago
Use Plus Sign at the beginning of each string
Code
$strBuffer = "Bob was here " + "not too long ago" Write-Host $strBuffer
Output
Image
Text
>powershell failure\string.plusSign.before.ps1 Cannot convert value "not too long ago" to type "System.Int32". Error: "Input string was not in a correct format." At failure\string.plusSign.before.ps1:2 char:17 + + "not too long ago" + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastFromStringToInteger Bob was here >
Explanation
- Powershell does not like to be surprised
- It throws up a bit on seeing the plus sign on the second line
Source Code Control
GitHub
DanielAdeniji/powershell.stringAcrossMultipleLines
https://github.com/DanielAdeniji/powershell.stringAcrossMultipleLines
Summary
Please use the here sign ( @” and “@) to preserve white spaces.
Or the more generic concatenation symbol ( plus sign [+] ) and line continuation symbol ( ` ) to merge string values.