【发布时间】:2012-11-07 06:36:29
【问题描述】:
我正在尝试将参数数组传递给 powershell 脚本文件。
我试图在命令行中像这样传递命令行。
Powershell -file "InvokeBuildscript.ps1" "z:\" "组件1","组件2"
但它并没有采用看起来的参数。我错过了什么?如何传递参数数组?
【问题讨论】:
我正在尝试将参数数组传递给 powershell 脚本文件。
我试图在命令行中像这样传递命令行。
Powershell -file "InvokeBuildscript.ps1" "z:\" "组件1","组件2"
但它并没有采用看起来的参数。我错过了什么?如何传递参数数组?
【问题讨论】:
简短回答:更多双引号可能会有所帮助...
假设脚本是“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 任务计划程序下;一个双引号替换为三个双引号
powershell.exe -Command .\test.ps1 -input_values 123,abc,"""x,y,z"""
希望对大家有所帮助
【讨论】:
-command 而不是-file。
-input_values 123,abc,'x,y,z'
-command而不是-file从批处理文件中调用Powershell.exe
也可以将数组变量作为命令行参数传递。示例:
考虑以下 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"
【讨论】:
试试
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
【讨论】: