Placing the following within a script will fail:
$MyString = @'
hello
@'
'@
bye
'@
write-host $MyString
The error returned is as follows:
At C:\scripts\test.ps1:6 char:1
+ '@
+ ~~
The string is missing the terminator: '.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Prefixing the nested @'
and '@
with a backtick (grave accent) does serve as an escape character, however it is also treated as literal, and therefore appears in the output of $MyString
.
Is there a correct way to escape a single quoted here-string within a single quoted here-string that does not interfere with the output?
NB:
I should have mentioned that the content of the outer here-string is dynamically populated, the content is supplied by another program to the powershell script as a command line argument. This is not reflected in the sample code as I didn't want to cloud the question with my very specific and somewhat niche implementation.
It's not all that likely that the outer here-string will contain an inner here-string (but it could happen), therefore I feel that some defensive programming is warranted in order to accommodate such an occurrence.