回答

6

你可以這樣做:

param(
    [string[]]$a, 
    [string[]]$d 
) 

write-host $a 
write-host ---- 
write-host $d 

然後就可以調用DoTheTask -a task1,task2 -d machine1,machine2

+0

manojlds:DoTheTask -a task1,task2 -d machine1,machine2這工作正常。有沒有一種方法可以在沒有(逗號)分隔的情況下給出格式。例如:DoTheTask -a task1 task2 -d machine1 machine2 machine3 –

+0

我自由地嘗試一個答案:它是可行的,但相當棘手。看看'$ MyInvocation'變量。使用它的屬性'Line','BoundParameters'和/或'UnboundArguments'應該允許你完全按照你喜歡的方式解析參數。 –

+2

我強烈建議您不要嘗試修改PowerShell的語法。 – JasonMArcher

0

你可以組織你的任務名稱和機器名以這樣的方式,他們可以放在一個單獨的字符串分隔符。

換句話說,你的-a參數是一個逗號分隔的任務名和你的-d參數是一串逗號分隔的機器名嗎?如果是這樣,那麼你所需要做的就是在腳本開始時將字符串解析爲它的組件。

+0

而不是傳遞字符串,然後分割等,只是通過作爲數組。看到我的答案。 – manojlds

0

如果您傳遞這些參數傳遞給腳本本身,你可以充分利用$args內部變量,雖然鍵/值映射將因爲PowerShell會將每個語句解釋爲一個參數,所以稍微複雜一點。我建議(和其他人一樣)使用另一個分隔符,以便您可以更輕鬆地進行映射。

不過,如果你想繼續做這種方式,您可以使用函數,如下面:

Function Parse-Arguments { 
    $_args = $script:args        # set this to something other than $script:args if you want to use this inside of the script. 
    $_ret = @{}   
    foreach ($_arg in $_args) { 
     if ($_arg.substring(0,1) -eq '-') { 
      $_key = $_arg; [void]$foreach.moveNext()  # set the key (i.e. -a, -b) and moves to the next element in $args, or the tasks to do for that switch 
      while ($_arg.substring(0,1) -ne '-') {  # goes through each task until it hits another switch 
       $_val = $_arg 
       switch($_key) { 
        '-a'  { 
          write-host "doing stuff for $_key" 
          $ret.add($_key,$_val)   # puts the arg entered and tasks to do for that arg. 
        } 

        # put more conditionals here 
       } 
      } 
     } 
    } 
} 
相關問題