[英]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.