什么时候可以在Powershell命令中使用换行符(换行符)来提高可读性 [英] When can I use newlines (line breaks) in my Powershell commands to improve readability

查看:541
本文介绍了什么时候可以在Powershell命令中使用换行符(换行符)来提高可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么知道何时可以在Powershell脚本中使用换行符/回车符?搜索此答案时,所有搜索结果都指向输出.我不在乎这种情况下的输出.我对格式化Powershell脚本以提高可读性的能力更感兴趣.

例如.下面是Powershell命令行的两个版本.一种有效,一种无效.在这种情况下,命令执行的操作并不重要.关键是我需要知道何时可以创建新行,何时不可以创建新行.

此命令行可以正常工作,因为它只是一条长长的单行:

& 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\arangoimp.exe' --file 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\tstImportJSON.json' --type json --collection users --progress true --overwrite true --server.username root --server.password password

由于脚本中间存在换行符,因此此命令行不起作用.

& 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\arangoimp.exe' --file 
'C:\Program Files\ArangoDB3 3.3.3\usr\bin\tstImportJSON.json'
--type json --collection users --progress true --overwrite true
--server.username root --server.password password

就我而言,在添加换行符以查看它们是否起作用之后,我只是在运行同一命令行的不同版本.我知道使用IF语句时可以开始换行.管道对象|时,我也可以使用换行符.我的假设是某处有一些Powershell脚本规则.我以为我曾经刚开始使用Powershell时曾经在某个地方看到过它们,但是现在不知道它在哪里.

解决方案

您可以使用`作为行继续符 [1] 在一行的末端 (不允许在其后加上空格),以便将其分布在多行上.

这是一个简化的示例:

& cmd.exe /c echo `
 hi `
 there

这等效于& cmd.exe /c echo hi there并产生hi there.

注意:

  • 由于`字符在视觉上都很微妙,并且语法很容易因意外在其后放置字符而被破坏,因此请考虑使用 array 作为替代方法-参见下文

  • 单个命令必须位于一行上,因此如果要跨多行分布它们,则需要`.

  • 但是,在管道您可以以| 结束该行,然后继续下一行,而无需`;例如:

    Get-Date | # Because the line ends with |, parsing continues on the next line.
      Select-Object Day
    

    • PowerShell [Core] v7 + 中,您也可以将|放在(非常) next 行的开头:

      Get-Date  # PS v7+ only
      | Select-Object Day
      

  • 此外,如果各个参数传递:它使用自动双引号来确保该参数被目标程序识别为参数.


    [1] `是PowerShell的通用转义字符.它位于行尾,它的功能略有不同:它可以有效地告诉我们,而不是转义紧随其后的换行符(这意味着保留作为文字). PowerShell对其进行删除,并将下一行视为当前行的延续.

    [2]此答案的较早形式建议基于数组的 PetSerAl 指出之前对于调用外部程序来说,按原样使用数组就足够了.
    虽然也可以使用splatting,但如果数组元素之一是停止解析符号--%(简言之:仅当splatting具有--%具有其特殊含义时),它的语义就有所不同. 但是,在调用 PowerShell 命令时,Splatting是一种有用的技术,主要以其 hash-table 形式(请参见上一链接).

    How do I know when I can use a New Lines/Carriage returns in my Powershell scripts? All of the search results when searching for this answer all point to the Output. I don't care about the output in this case. I am more interested in my ability to format my Powershell scripts for readability.

    For Example. Two versions of a Powershell command line below. One works and one doesn't. What the command does is unimportant in this case. The point is I am needing to know when I'm allowed to create a new line and when I am not.

    This command line Works as it's just one long single line:

    & 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\arangoimp.exe' --file 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\tstImportJSON.json' --type json --collection users --progress true --overwrite true --server.username root --server.password password
    

    This command line does NOT work due to the fact that there is a New Line in the middle of the script.

    & 'C:\Program Files\ArangoDB3 3.3.3\usr\bin\arangoimp.exe' --file 
    'C:\Program Files\ArangoDB3 3.3.3\usr\bin\tstImportJSON.json'
    --type json --collection users --progress true --overwrite true
    --server.username root --server.password password
    

    In my case I'm just running different versions of the same command line after adding line breaks to see if they work or not. I know that I can begin a New Line when using an IF statement. I can also use New Lines when piping an object |. My assumption is that somewhere there is a list of Powershell scripting rules. I thought I had seen them somewhere once upon a time when I originally began getting into Powershell but no clue where it is now.

    解决方案

    You can use ` as the line-continuation character[1] at the very end of a line (not even whitespace is allowed after it) in order to spread it across multiple lines.

    Here's a simplified example:

    & cmd.exe /c echo `
     hi `
     there
    

    This is the equivalent of & cmd.exe /c echo hi there and yields hi there.

    Note:

    • Since the ` character is both visually subtle and the syntax is easy to break by accidentally placing characters after it, consider using an array as an alternative - see below.

    • Individual commands must be on a single line and therefore need ` if you want to spread them across multiple lines, as shown above.

    • However, in a pipeline you may end the line with | and continue on the next line, without needing the `; e.g.:

      Get-Date | # Because the line ends with |, parsing continues on the next line.
        Select-Object Day
      

      • In PowerShell [Core] v7+, you may alternatively place the | at the start of the (very) next line:

        Get-Date  # PS v7+ only
        | Select-Object Day
        

    • Additionally, if individual arguments create a new parsing context in expression mode - such as an inherently multi-line capable (...) expression or a script block ({...}) passed to a cmdlet - you're also free to spread the expression across multiple lines; e.g.:

      1, 2, 3 | ForEach-Object { # { starts a multiline-aware context
        $_ + 1
      }
      

    • A hybrid case is an array-literal argument, which allows you to break a command after an interior element's , separator:

      Get-Date | Select-Object -Property Day,
                                         Year
      

    • Statements that start in expression mode always allow spreading across multiple lines (though embedded command-mode statements are subject to the usual limitations):

      $foo =         # an assignment is parsed in expression mode
              'bar'  
      


    Alternatively, consider the use of an array[2] to pass the arguments, which allows you to use multiline expression-mode syntax to define the arguments as individual array elements beforehand:

    # Construct the array of arguments (using multiline expression syntax)...
    $arguments = '/c',
                 'echo',
                 'hi there'
    
    # ... and pass it to cmd.exe
    & cmd.exe $arguments 
    

    Note: Array element hi there is passed as "hi there" by PowerShell: it employs automatic double-quoting to ensure that the argument is recognized as a single argument by the target program.


    [1] ` is PowerShell's general-purpose escape character. Placed at the very end of a line, its function is subtly different: instead of escaping the newline that follows (which would mean retaining it as a literal), it effectively tells PowerShell to remove it and treat the next line as the continuation of the current one.

    [2] An earlier form of this answer recommended array-based splatting, before PetSerAl pointed out that for invoking external programs it's sufficient to use an array as-is.
    While splatting can be used too, its semantics are subtly different if one of the array element is --%, the stop-parsing symbol (in short: only when splatting does --% have its special meaning).
    Splatting is a useful technique when calling PowerShell commands, however, primarily in its hash-table form (see previous link).

    这篇关于什么时候可以在Powershell命令中使用换行符(换行符)来提高可读性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆