Powershell 似乎在参数数组中得到错误数量的元素

Powershell seems to get the wrong number of elements in a param array

假设我有(在文件 test.ps1 中):

param (
    [string[]] $one
)
Write-Host $one.Count

如果我这样做:

powershell -File test.ps1 -one "hello","cat","Dog"

我得到:

1

但我预计:

3

为什么?

“-one”作为整个字符串传入,因为转换发生在调用方法之前。

您也可以像下面这样称呼它

powershell -Command {.\test.ps1 -one "hello","cat","Dog"}

补充:

  • 通过 PowerShell CLI 数组 传递给 PowerShell 脚本的唯一方法 (powershell.exe; pwsh 对于 PowerShell Core) 是 使用 -Commmand (-c).

    • 相比之下,-File 将参数解释为文字值 识别数组、变量引用 ($foo), ...;在手头的例子中,脚本最终看到一个 单个字符串 和文字内容 hello,cat,Dog (由于双引号删除)。
  • 来自内部 PowerShell:

    • 使用-Command脚本块{ ... }),如图, which not only simplifies the syntax (just use regular syntax inside the block), but produces type-rich output (not just strings, as with other external programs), because the target PowerShell instance uses the CLIXML serialization format to output its results, which the calling session automatically deserializes, the same way that PowerShell remoting / background jobs work (as with the latter, however, the type fidelity of the deserialization is invariably limited; see ).

    • 但是请注意,在 PowerShell 中,您通常不需要 CLI,它会创建一个(昂贵的)子进程,并且可以 直接调用 *.ps1 脚本文件 :

      • .\test.ps1 -one hello, cat, Dog
  • 来自 外部 PowerShell - 通常 cmd.exe / 一个批处理文件 - -Command 与包含要执行的 PowerShell 代码的 单双引号字符串 一起使用,前提是 使用脚本块不受支持从外面.

    • powershell -Command ".\test.ps1 -one hello, cat, Dog"

请注意,使用 -Command,就像在 PowerShell 中直接调用一样,您 必须 使用 .\test.ps1 而不仅仅是 test.ps1命令在当前目录 中执行该名称的文件 ,这是一项安全功能。

另请注意,对于简单的参数值,"..." - 将它们括起来是可选的,这就是为什么上面的命令只使用 hello, cat, Dog 而不是 "hello", "cat", "Dog" 的原因;事实上,使用嵌入的 " 个字符。在整个 "..." 命令字符串中可能会变得非常棘手 - 请参阅 .