Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell似乎在参数数组中获取了错误的元素数_Powershell_Powershell 4.0 - Fatal编程技术网

Powershell似乎在参数数组中获取了错误的元素数

Powershell似乎在参数数组中获取了错误的元素数,powershell,powershell-4.0,Powershell,Powershell 4.0,假设我有(在文件test.ps1中): 如果我这样做: powershell -File test.ps1 -one "hello","cat","Dog" 我得到: 1 但我希望: 3 为什么?在调用方法之前进行转换时,“-one”作为整个字符串传递 你也可以这样称呼它 powershell -Command {.\test.ps1 -one "hello","cat","Dog"} 补充: 通过PowerShell CLI将数组传递给PowerShell脚本的唯一方法(PowerS

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

如果我这样做:

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核心)是使用
    -Commmand

    • 相比之下,
      -File
      将参数解释为文字值,并且不识别数组、变量引用(
      $foo
      )、。。。;在本例中,脚本最终看到一个字符串,其中包含文字内容
      hello,cat,Dog
      (由于删除了双引号)
  • 从PowerShell内部的

    • 如图所示,对脚本块使用
      -Command
      {…}
      ),这不仅简化了语法(只需在块内使用常规语法),而且产生了类型丰富的输出(不只是字符串,与其他外部程序一样),因为目标PowerShell实例使用CLIXML序列化格式输出其结果,调用会话将自动反序列化,这与PowerShell远程处理/后台作业的工作方式相同(但是,与后者一样,反序列化的保真度总是有限的)

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

      • \test.ps1-一声你好,猫,狗
  • 从外部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”
;事实上,使用嵌入的
字符。在总体
”…“
命令字符串可能会变得相当棘手-请参阅

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