Blank & TAB Problem Inside HereDOC in Powershell (Or An alternative way for long text)

35 Views Asked by At

How can I leave spaces and tabs between heredoc tags?

My Functions

function random_ascii () {    $text=@"
        _    ____   ____ ___ ___      _         _        _             _     _           
       / \  / ___| / ___|_ _|_ _|    / \   _ __| |_     / \   _ __ ___| |__ (_)_   _____ 
      / _ \ \___ \| |    | | | |    / _ \ | '__| __|   / _ \ | '__/ __| '_ \| \ \ / / _ \
     / ___ \ ___) | |___ | | | |   / ___ \| |  | |_   / ___ \| | | (__| | | | |\ V /  __/
    /_/   \_\____/ \____|___|___| /_/   \_\_|   \__| /_/   \_\_|  \___|_| |_|_| \_/ \___|
    "@    write-output $text }

random_ascii

I cannot put tab or blank last ending tag for heredoc -- "@ --, why does it crash when i do this

$text1 = @" this is wrong, why is this wrong usage? "@

$text2 = @"
    This is also wrong,
    "@

$text3 = @" this is OK
"@

Another Example:

    $Menu1 = @'
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
    when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting,
    remaining essentially unchanged.
    '@

$Menu2 = "Hello Wold"

The command ($Menu2) does not work because I put whitespace characters in the heredoc value $Menu1. I want to put spaces in the code block (including start and end tags) as it gives an ugly look, but I can't. Is there a way I can do that?

enter image description here

1

There are 1 best solutions below

11
Mathias R. Jessen On

From the about_Quoting_Rules help topic (emphasis added):

A here-string:

  • spans multiple lines
  • begins with the opening mark followed by a newline
  • ends with a newline followed by the closing mark
  • includes every line between the opening and closing marks as part of a single string

That is, the newline following the opening mark (@"<newline>) and preceding the closing mark (<newline>"@) are part of the string literal boundaries.

So if you want to last line of the constructed string value to contain, then it has to go before that last newline (`t is the escape sequence for the TAB character in an expandable string):

@"
<ASCII art goes here>
`t
"@

With your second example, you can simply keep the inline whitespace - all you need to do is remove the spaces before the '@:

$Menu1 = @'
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
    when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting,
    remaining essentially unchanged.
'@ # now the parser won't complain

$Menu2 = "Hello Wold"