共用方式為


Cmdlet 動態參數

Cmdlet 可以定義特殊條件下使用者可用的參數,例如當另一個參數的自變數是特定值時。 這些參數會在運行時間新增,並稱為動態參數,因為它們只會在需要時新增。 例如,您可以設計只有在指定特定 switch 參數時,才能新增數個參數的 Cmdlet。

備註

提供者和PowerShell函式也可以定義動態參數。

PowerShell Cmdlet 中的動態參數

PowerShell 在其數個提供者 Cmdlet 中使用動態參數。 例如,當 Path 參數指定 憑證 提供者路徑時,Get-ItemGet-ChildItem Cmdlet 會在運行時間新增 CodeSigningCert 參數。 如果 Path 參數指定不同提供者的路徑,則無法使用 CodeSigningCert 參數。

下列範例示範在執行 Get-Item 時,如何在運行時間新增 CodeSigningCert 參數。

在此範例中,PowerShell 運行時間已新增 參數,且 Cmdlet 成功。

Get-Item -Path Cert:\CurrentUser -CodeSigningCert
Location   : CurrentUser
StoreNames : {SmartCardRoot, UserDS, AuthRoot, CA...}

在此範例中,指定 FileSystem 磁碟驅動器,並傳回錯誤。 錯誤訊息指出找不到 CodeSigningCert 參數。

Get-Item -Path C:\ -CodeSigningCert
Get-Item : A parameter cannot be found that matches parameter name 'CodeSigningCert'.
At line:1 char:37
+  Get-Item -Path C:\ -CodeSigningCert <<<<
--------
    CategoryInfo          : InvalidArgument: (:) [Get-Item], ParameterBindingException
    FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetItemCommand

支援動態參數

若要支援動態參數,Cmdlet 程式代碼中必須包含下列元素。

介面

System.Management.Automation.IDynamicParameters。 這個介面提供擷取動態參數的方法。

例如:

public class SendGreetingCommand : Cmdlet, IDynamicParameters

方法

System.Management.Automation.IDynamicParameters.GetDynamicParameters。 這個方法會擷取包含動態參數定義的物件。

例如:

 public object GetDynamicParameters()
 {
   if (employee)
   {
     context= new SendGreetingCommandDynamicParameters();
     return context;
   }
   return null;
}
private SendGreetingCommandDynamicParameters context;

班級

類別,定義要加入的動態參數。 這個類別必須包含每個參數的 Parameter 屬性,以及 Cmdlet 所需的任何選擇性 AliasValidation 屬性。

例如:

public class SendGreetingCommandDynamicParameters
{
  [Parameter]
  [ValidateSet ("Marketing", "Sales", "Development")]
  public string Department
  {
    get { return department; }
    set { department = value; }
  }
  private string department;
}

如需支援動態參數之 Cmdlet 的完整範例,請參閱 如何宣告動態參數

另請參閱