Powershell中的HereDOC内部的空白和TAB问题(或长文本的替代方法)

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

提问人:Ichigo Kurosaki 提问时间:6/28/2023 最后编辑:Ichigo Kurosaki 更新时间:6/28/2023 访问量:20

问:

如何在 heredoc 标签之间留下空格和制表符?

我的职能

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

random_ascii

我不能为 heredoc 放置制表符或空白的最后一个结束标签 -- “@ --,为什么当我这样做时它会崩溃

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

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

$text3 = @" this is OK
"@

另一个例子:

    $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"

命令 ($Menu 2) 不起作用,因为我输入了空格字符 在 HereDoc 值 $Menu 1 中。我想在代码块中放置空格(包括开始和结束标记)作为 它给人一种丑陋的外观,但我不能。有什么办法可以做到这一点吗?

enter image description here

PowerShell 选项卡 heredoc

评论


答:

0赞 Mathias R. Jessen 6/28/2023 #1

来自about_Quoting_Rules帮助主题(强调后加):

here-string:

  • 跨越多条线
  • 以开始标记开头,后跟换行符
  • 以换行符结尾,后跟结束标记
  • 将开始标记和结束标记之间的每行都作为单个字符串的一部分

也就是说,开始标记 () 之后和结束标记 () 之前的换行符是字符串文本边界的一部分。@"<newline><newline>"@

因此,如果要包含构造字符串值的最后一行,则它必须位于最后一个换行符之前( 是可扩展字符串中 TAB 字符的转义序列):`t

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

在第二个示例中,您可以简单地保留内联空格 - 您需要做的就是删除以下内容之前的空格:'@

$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"

评论

0赞 Ichigo Kurosaki 6/28/2023
实际上,我遇到的问题是,当我在代码块的最后一行添加空白标签时,它会给出编译错误。
0赞 Mathias R. Jessen 6/28/2023
@IchigoKurosaki 你读过文档的解释吗?换行符和结束符之间不能有任何其他空格字符。确切的错误消息是什么?
0赞 Ichigo Kurosaki 6/28/2023
是的,我已经读过了。因此,我试图找到一种替代方法,以便在这些标签之间放置空格字符或其他替代方法。因为它给我的代码块带来了非常丑陋的外观。
0赞 Mathias R. Jessen 6/28/2023
@IchigoKurosaki 只需要删除最后一个换行符和结束标记之间的空格 - 前一行的前导空格仍然是字符串文本的一部分。只要避免在源代码中缩进/,你就会没事的。查看更新的答案"@'@
0赞 Ichigo Kurosaki 6/28/2023
我知道,但我坚持要在这里放一个空格==>空白 '@