[英]Pass array to PowerShell script executed with -File argument
我有简单的脚本,它采用数组参数:
param(
[Parameter(Mandatory=$true)]
[string[]]$keys
)
for ($i = 0; $i -lt $keys.Length; ++$i) {
Write-Host "$i. $($keys[$i])"
}
我需要通过powershell和-File参数执行它(为了解决TeamCity错误),如下所示:
powershell.exe -File Untitled2.ps1 -keys a
如何将参数作为数组传递给我的脚本? 只要我传递单个键,它就可以正常工作,但它不想占用多个元素。
我试过跟随其他人:
powershell.exe -File Untitled2.ps1 -keys a,b
powershell.exe -File Untitled2.ps1 -keys:a,b
powershell.exe -File Untitled2.ps1 -keys $keys # where $keys is an array
无论我尝试过什么,我都有“无法找到位置参数”错误,或者所有键都连接在第一个数组元素中。
有任何想法吗?
这是另一种尝试。 请注意参数声明中的ValueFromRemainingArguments=$true
:
param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
[string[]]$keys)
for ($i = 0; $i -lt $keys.Length; ++$i) {
Write-Host "$i. $($keys[$i])"
}
然后我使用-file参数通过powershell.exe调用脚本:
powershell.exe -File d:\scripts\array.ps1 "1" "a" "c"
这可以将所有这些参数作为数组传递,输出为:
0. 1
1. a
2. c
如果您需要传递其他参数,可以按常规方式命名,例如:
param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
[string[]]$keys,
[string] $dummy)
您可以传递其他参数,例如:
powershell.exe -File d:\scripts\array.ps1 "1" "a" "c" -dummy "Z"
在这种情况下, $dummy
参数将接收值Z
而"1" "a" "c"
仍将作为数组分配给$keys
。
因此,如果更改脚本以显示$dummy
的值以及其他我得到的值:
0. 1
1. a
2. c
Dummy param is z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.