Krz*_*tof 9 arrays parameters powershell
我有简单的脚本,它采用数组参数:
param(
[Parameter(Mandatory=$true)]
[string[]]$keys
)
for ($i = 0; $i -lt $keys.Length; ++$i) {
Write-Host "$i. $($keys[$i])"
}
Run Code Online (Sandbox Code Playgroud)
我需要通过powershell和-File参数执行它(为了解决TeamCity错误),如下所示:
powershell.exe -File Untitled2.ps1 -keys a
Run Code Online (Sandbox Code Playgroud)
如何将参数作为数组传递给我的脚本?只要我传递单个键,它就可以正常工作,但它不想占用多个元素.
我试过跟随其他人:
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
Run Code Online (Sandbox Code Playgroud)
无论我尝试过什么,我都有"无法找到位置参数"错误,或者所有键都连接在第一个数组元素中.
有任何想法吗?
这是另一种尝试.请注意ValueFromRemainingArguments=$true参数声明中的:
param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
[string[]]$keys)
for ($i = 0; $i -lt $keys.Length; ++$i) {
Write-Host "$i. $($keys[$i])"
}
Run Code Online (Sandbox Code Playgroud)
然后我使用-file参数通过powershell.exe调用脚本:
powershell.exe -File d:\scripts\array.ps1 "1" "a" "c"
Run Code Online (Sandbox Code Playgroud)
这可以将所有这些参数作为数组传递,输出为:
0. 1
1. a
2. c
Run Code Online (Sandbox Code Playgroud)
如果您需要传递其他参数,可以按常规方式命名,例如:
param([parameter(Mandatory=$true,ValueFromRemainingArguments=$true)]
[string[]]$keys,
[string] $dummy)
Run Code Online (Sandbox Code Playgroud)
您可以传递其他参数,例如:
powershell.exe -File d:\scripts\array.ps1 "1" "a" "c" -dummy "Z"
Run Code Online (Sandbox Code Playgroud)
$dummy在这种情况下,参数将接收值,Z而值"1" "a" "c"仍将$keys作为数组分配.
因此,如果更改脚本以显示$dummy其余的值,我得到:
0. 1
1. a
2. c
Dummy param is z
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5889 次 |
| 最近记录: |