2012-06-21 28 views
8

Rất đơn giản, làm thế nào để khởi tạo params phần của Powershell Script của tôi để tôi có thể có một đối số dòng lệnh nhưCó một tham số tùy chọn mà yêu cầu thông số khác để có mặt

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]] 

Vì vậy, lần duy nhất tôi có thể sử dụng -bar là khi foo2 có ben được xác định.

Nếu -bar là không phụ thuộc vào -foo2 Tôi chỉ có thể làm

[CmdletBinding()] 
param (
    [Parameter(Mandatory=$true)] 
    [string]$foo1, 

    [string]$foo2, 

    [string]$bar 
) 

Tuy nhiên tôi không biết phải làm gì để làm cho điều đó tham số phụ thuộc.

+4

Xem câu hỏi này: http://stackoverflow.com/questions/10748978/conditional-powershell-parameters/10749238#10749238 –

Trả lời

9

đọc của tôi về câu hỏi ban đầu là hơi khác nhau của CB. Từ

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]] 

Đối số đầu tiên $ foo1 luôn bắt buộc, trong khi thanh chỉ định $ foo2 cũng phải được chỉ định.

Vì vậy, mã hóa của tôi về nó sẽ là đặt $ foo1 trong cả hai bộ tham số.

function Get-Foo 
{ 
[CmdletBinding(DefaultParameterSetName="set1")] 
param (
    [Parameter(ParameterSetName="set1", Mandatory=$true, Position=0)] 
    [Parameter(ParameterSetName="set2", Mandatory=$true, Position=0) ] 
    [string]$foo1, 
    [Parameter(ParameterSetName="set2", Mandatory=$true)] 
    [string]$foo2, 
    [Parameter(ParameterSetName="set2", Mandatory=$false)] 
    [string]$bar 
) 
    switch ($PSCmdlet.ParameterSetName) 
    { 
     "set1" 
     { 
      $Output= "Foo is $foo1" 
     } 
     "set2" 
     { 
      if ($bar) { $Output= "Foo is $foo1, Foo2 is $foo2. Bar is $Bar" } 
      else  { $Output= "Foo is $foo1, Foo2 is $foo2"} 
     } 
    } 
    Write-Host $Output 
} 

Get-Foo -foo1 "Hello" 
Get-Foo "Hello with no argument switch" 
Get-Foo "Hello" -foo2 "There is no bar here" 
Get-Foo "Hello" -foo2 "There" -bar "Three" 
Write-Host "This Stops for input as foo2 is not specified" 
Get-Foo -foo1 "Hello" -bar "No foo2" 

Sau đó, bạn sẽ nhận được kết quả sau khi bạn chạy phần trên.

Foo is Hello 
Foo is Hello with no argument switch 
Foo is Hello, Foo2 is There is no bar here 
Foo is Hello, Foo2 is There. Bar is Three 
This Stops for input as foo2 is not specified 

cmdlet Get-Foo at command pipeline position 1 
Supply values for the following parameters: 
foo2: Typedfoo2 
Foo is Hello, Foo2 is Typedfoo2. Bar is No foo2 
7

Bạn cần ParameterSet, đọc vào đây để biết thêm về nó:

http://msdn.microsoft.com/en-us/library/windows/desktop/dd878348(v=vs.85).aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/30/use-parameter-sets-to-simplify-powershell-commands.aspx

mẫu mã của bạn:

[CmdletBinding(DefaultParameterSetName="set1")] 
param (
    [Parameter(ParameterSetName="set1", Mandatory=$true)] 
    [string]$foo1, 
    [Parameter(ParameterSetName="set2", Mandatory=$true)] 
    [string]$foo2, 
    [Parameter(ParameterSetName="set2")] 
    [string]$bar 
) 
Các vấn đề liên quan