2012-10-18 49 views
3

動態參數我有一個動態的參數有問題:問題在PowerShell中

function get-foo { 
[cmdletBinding()] 
param(
    [parameter(Mandatory=$true)] 
    $Name 
) 
DynamicParam { 
if($Name -like 'c*') { 
$Attributes = New-Object 'Management.Automation.ParameterAttribute' 
$Attributes.ParameterSetName = '__AllParameterSets'    
$Attributes.Mandatory = $false 
$AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]' 
$AttributesCollection.Add($Attributes) 
$Dynamic = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern','system.object',$AttributeCollection) 
$ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary'   
$ParamDictionary.Add("pattern", $Dynamic) 
$ParamDictionary 
} 
} 
end { 
    if($test) { 
     return $Name -replace '\b\w',$test 
    } 
    $name 
} 
} 

它檢測到我的模式參數,但它返回一個錯誤;

ps c:\> get-foo -Name cruze -pattern 123 
get-foo : Le paramètre « pattern » ne peut pas être spécifié dans le jeu de paramètres « __AllParameterSets  
». 
Au niveau de ligne : 1 Caractère : 8 
+ get-foo <<<< -Name cruze -pattern u 
    + CategoryInfo   : InvalidArgument: (:) [get-foo], ParameterBindingException 
    + FullyQualifiedErrorId : ParameterNotInParameterSet,get-foo 

如何解決問題?

+0

您能否翻譯錯誤信息? –

+0

@Roman Kuzmin:無法在參數集「__ AllParameterSets – Why

+0

」中指定參數「pattern」對不起,我打算通過添加翻譯來編輯您的問題 –

回答

1

$AttributeCollection替換爲$AttributesCollection('s'缺失)。

使用Set-StrictMode爲了捕捉這些錯別字:)


至於劇本,我覺得還有其他一些問題,太。這裏是正確的和正在使用的版本:

function get-foo { 
    [cmdletBinding()] 
    param(
     [parameter(Mandatory=$true)] 
     $Name 
    ) 
    DynamicParam { 
     if ($Name -like 'c*') { 
      $Attributes = New-Object 'Management.Automation.ParameterAttribute' 
      $Attributes.ParameterSetName = '__AllParameterSets' 
      $Attributes.Mandatory = $false 
      $AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]' 
      $AttributesCollection.Add($Attributes) 
      $Pattern = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern', [string], $AttributesCollection) 
      $ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary' 
      $ParamDictionary.Add("pattern", $Pattern) 
      $ParamDictionary 
     } 
    } 
    end { 
     if ($Name -like 'c*') { 
      if ($Pattern.IsSet) { 
       return $Name -replace '\b\w', $Pattern.Value 
      } 
     } 
     $name 
    } 
} 
+0

感謝羅馬,並添加's'沒有錯誤: )但是腳本不工作,它總是返回'cop';「PS> get-foo -name cop -pattern x」有什麼想法?謝謝 – Why

+0

@Why看起來'$ test'它永遠不會涉及並獲得價值。 –

+0

@Christian,youpi ....我發現了一個問題,「if($ PSBoundParameters.test){#code}」謝謝:) – Why