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

25

我正在尝试将参数数组传递给PowerShell脚本文件。

我曾在命令行中尝试过以下方式进行命令行传递。

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

但似乎没有接受参数。我漏掉了什么?如何传递参数数组?

3个回答

29

简短回答:加入更多的双引号可能有帮助……

假设脚本名为"test.ps1"

param(

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

)
$PSBoundParameters

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

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

.\test.ps1 -input_values 123,abc,"x,y,z"

在Windows命令提示符控制台或Windows任务计划程序中,双引号将替换为3个双引号

powershell.exe -Command .\test.ps1 -input_values 123,abc,"""x,y,z"""

希望这能对一些人有所帮助


13
这里的技巧是使用显式的“-command”而不是“-file”。 - Mike Makarov
我能够使用“-input_values 123,abc,'x,y,z'” - Slogmeister Extraordinaire
2
重申一下,Mike在这个答案中提到的是我错过的。对我有用的是在批处理文件中使用-command而不是-file来调用Powershell.exe。 - Rudimentary
如果您无法控制test.ps1,则此方法无法帮助您。 - Ben Jaguar Marshall

11

尝试

Powershell -command "c:\pathtoscript\InvokeBuildscript.ps1" "z:\" "Component1,component2"

如果test.ps1是:

$args[0].GetType()
$args[1].gettype()

在 DOS shell 中调用它的方式如下:

C:\>powershell -noprofile -command  "c:\script\test.ps1" "z:" "a,b"

返回值:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
True     True     Object[]                                 System.Array

1

你也可以将数组变量作为命令行参数传递。示例:

考虑以下 Powershell 模块

文件:PrintElements.ps1

Param(
    [String[]] $Elements
)

foreach($element in $Elements)
{
   Write-Host "element: $element"
}

要使用上述PowerShell模块,请使用以下步骤:
#Declare Array Variable
[String[]] $TestArray = "Element1", "Element2", "Element3"

#Call the powershell module
.\PrintElements.ps1 $TestArray

如果您想将TestArray连接并作为一个以空格分隔的字符串传递,那么您可以通过将参数括在引号中来调用PS模块,如下所示:

#Declare Array Variable
[String[]] $TestArray = "Element1", "Element2", "Element3"

#Call the powershell module
.\PrintElements.ps1 "$TestArray"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接