【问题标题】:Must PowerShell scripts be called using only a single line?必须仅使用一行调用 PowerShell 脚本吗?
【发布时间】:2010-01-13 15:09:38
【问题描述】:

我有一些 PowerShell 脚本可以接受许多长参数,例如,

myScript.ps1 -completePathToFile "C:\...\...\...\file.txt" -completePathForOutput "C:\...\...\...\output.log" -recipients ("me@me.com") -etc.

除非所有参数都在一行上,否则我似乎无法让 PowerShell 运行此类脚本。有没有办法像这样调用脚本?

myScript.ps1
  -completePathToFile "C:\...\...\...\file.txt"
  -completePathForOutput "C:\...\...\...\output.log"
  -recipients (
    "me@me.com",
    "him@him.com"
   )
  -etc

缺乏可读性让我发疯了,但脚本确实需要这个参数。

【问题讨论】:

    标签: command-line powershell parameters


    【解决方案1】:

    PowerShell 认为该命令在行尾是完整的,除非它看到某些字符,如竖线、左括号或左花括号。只需在每行的末尾添加一个续行字符 ` `,但要确保该续行字符后没有空格:

    myScript.ps1 `
      -completePathToFile "C:\...\...\...\file.txt" `
      -completePathForOutput "C:\...\...\...\output.log" `
      -recipients (
        "me@me.com", `
        "him@him.com" `
       ) 
    

    如果您使用的是 PowerShell 2.0,您还可以将这些参数放在哈希表中并使用 splatting,例如:

    $parms = @{
        CompletePathToFile   = 'C:\...\...\...\file.txt'
        CompletPathForOutput = 'C:\...\...\...\output.log'
        Recipients           = 'me@me.com','him@him.com'
    }
    myScript.ps1 @parms
    

    【讨论】:

    • 我发现逗号操作符足以让Powershell继续下一行,只要它实际上将其解析为操作符而不是以','结尾的字符串参数跨度>
    • 谢谢。我确定还有其他字符向 PowerShell 表明还有更多。不确定是否有这些记录的清单。
    • Keith,谢谢你提醒我在 Posh 中有一个飞溅。我读了它然后忘记了。现在我看到它为如何使用脚本/函数参数带来了很多可能性。
    猜你喜欢
    • 2015-07-07
    • 2021-03-30
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    相关资源
    最近更新 更多