提问人:Carbon 提问时间:1/18/2019 最后编辑:Carbon 更新时间:11/17/2023 访问量:182
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"}
为了补充 Kevin Smith 的有用答案,该答案仅适用于 PowerShell 内部:
通过 PowerShell CLI(适用于 Windows PowerShell,适用于 PowerShell (Core) 7+)将数组传递给 PowerShell 脚本的唯一方法是使用 -
Commmand
(-c
)。powershell.exe
pwsh
- 相比之下,
-File
将参数解释为文本值,并且不识别数组、变量引用 ()、...;在手头的情况下,脚本最终会看到一个带有文本内容的字符串(由于删除了双引号)。$foo
hello,cat,Dog
- 相比之下,
在 PowerShell 内部:
将
-Command
与脚本块 () 一起使用,如 Kevin 的回答所示,这不仅简化了语法(只需在块中使用常规语法),而且生成类型丰富的输出(不仅仅是字符串,就像其他外部程序一样),因为目标 PowerShell 实例使用 CLIXML 序列化格式输出其结果,调用会话会自动反序列化这些结果。 与 PowerShell 远程处理/后台作业的工作方式相同(但是,与后者一样,反序列化的类型保真度总是受到限制;请参阅此答案)。{ ... }
但是,请注意,在 PowerShell 中,通常不需要 CLI,它会创建一个(成本高昂的)子进程,并且只能直接调用
*.ps1
脚本文件:.\test.ps1 -one hello, cat, Dog
在外部 PowerShell(通常为批处理文件)中,将
-Command
与包含要执行的 PowerShell 代码的单双引号字符串一起使用,因为不支持从外部使用脚本块。cmd.exe
powershell -Command ".\test.ps1 -one hello, cat, Dog"
如果数组元素本身需要引号,请将它们括在(对于逐字值)或(即转义,对于可扩展字符串):
'...'
\"...\"
"..."
powershell -Command ".\test.ps1 -one 'hello there', cat, \"Dog food\""
注意:在极端情况下,转义可能会导致呼叫时出现问题 - 有关解决方法,请参阅此答案。
\"
cmd.exe
请注意,与在 PowerShell 中直接调用一样,必须使用 .\test.ps1 而不仅仅是 test.ps1
,才能在当前目录中按该名称执行文件,这是一项安全功能。
-Command
另请注意,对于简单的参数值,-括起来它们是可选的,这就是为什么上面的命令使用 just 而不是 ."..."
hello, cat, Dog
"hello", "cat", "Dog"
评论