2015-12-25 36 views
0

假設您有一個PowerShell腳本,它接受可變數量的參數。你想把任何不是選項的東西當作文件名。在bash中,這是很容易:如何獲取PowerShell中的其餘參數?

files=() # Empty array of files 

while [ $# -gt 0 ] 
do 
    case "$1" in 
     -option1) do_option1=true ;; 
     -option2) option2_flag="$2" shift ;; 
     *) # Doesn't match anything else 
      files+=("$1") ;; 
    esac 
    shift 
done 

什麼會使用PowerShell的Param()是等效代碼?這對於消除大部分樣板解析代碼是很有用的,但是如何使用它來解析文件?例如,這個工程:

Param(
    [switch]$Option1, 
    [string]$Option2, 
    [string[]]$Files 
); 

,但你必須調用腳本就像script.ps1 the,file,names得到它正確分析。如果你打電話script.ps1 the file names它不會被識別。

我也試過$PSBoundParameters,但那也不管用。

爲什麼會發生這種情況,我該如何解決這個問題?謝謝!

+2

'[參數(ValueFromRemainingArguments)]' – PetSerAl

回答

0

使用Mandatory=$True作爲您的文件名參數,使用Mandatory=$False作爲您的選項。

Param(
    [Parameter(Mandatory=$false)] 
    [switch]$Option1, 
    [Parameter(Mandatory=$false)] 
    [string]$Option2, 
    [Parameter(Mandatory=$True)] 
    [string[]]$Files 
); 

所以,當你打電話給你的功能,你可以做

yourFunc "filename" # only pass value for $files 
yourFUnc -option1 "value" -option2 "value" -files "value" # pass value to all of your paras 
相關問題