如何将参数数组传递给Powershell命令行

Sam*_*abu 13 powershell powershell-2.0

我试图将数组参数传递给powershell脚本文件.

我试图在命令行中传递这样的命令行.

Powershell -file"InvokeBuildscript.ps1""z:\""Component1","component2"

但它似乎没有采取参数.我错过了什么?如何传递参数数组?

小智 15

简短回答:更多双引号可能会有所帮助......

假设脚本是"test.ps1"

param(

    [Parameter(Mandatory=$False)]
    [string[]] $input_values=@()

)
$PSBoundParameters
Run Code Online (Sandbox Code Playgroud)

假设想传递数组@(123,"abc","x,y,z")

在Powershell控制台下,将多个值作为数组传递

.\test.ps1 -input_values 123,abc,"x,y,z"
Run Code Online (Sandbox Code Playgroud)

在Windows命令提示符控制台或Windows任务计划程序下; 双引号被3个双引号取代

powershell.exe -Command .\test.ps1 -input_values 123,abc,"""x,y,z"""
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助一些人

  • 这里的技巧是使用显式的`-command`而不是`-file`. (9认同)
  • 重申一下,迈克指出的,因为我在这个答案中也错过了这一点。对我有用的是使用“-command”而不是“-file”从批处理文件中调用 Powershell.exe (2认同)

CB.*_*CB. 9

尝试

Powershell -command "c:\pathtoscript\InvokeBuildscript.ps1" "z:\" "Component1,component2"
Run Code Online (Sandbox Code Playgroud)

如果test.ps1是:

$args[0].GetType()
$args[1].gettype()
Run Code Online (Sandbox Code Playgroud)

从dos shell调用它,如:

C:\>powershell -noprofile -command  "c:\script\test.ps1" "z:" "a,b"
Run Code Online (Sandbox Code Playgroud)

回报:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
True     True     Object[]                                 System.Array
Run Code Online (Sandbox Code Playgroud)