使用System.Management.Automation将数组传递给c#中的cmdlet

时间:2016-05-12 23:17:19

标签: c# powershell

我正在用C#编写一个cmdlet,我希望能够在三个强制参数之后传递一个数组,例如

Set-PersistedVariables "IDKey1", "IDKey2", "C:\temp\Store", "VarName1", "VarValue1", "VarName2", "VarValue2", "VarNameN", "VarValueN"

或类似的东西。知道如何在C#Cmdlet中构造我的参数并在Powershell中编写调用吗?

我确实找到了Powershell hashtables as argument to custom cmdlet in C#,但是如果这适用于我的情况则会丢失。

1 个答案:

答案 0 :(得分:0)

您可以声明从pipline读取的数组参数。

[Cmdlet("Set", "PersistedVariables")]
public class SetPersistedVariablesCmdlet : Cmdlet
{
  [Parameter(ValueFromPipeline = true, Position = 0)]
  public string[] InputArray {get;set;}
  protected override void ProcessRecord()
  {
    var yourArray = InputArray;
  }
}

以下列形式声明的参数:

Set-PersistedVariables "IDKey1", "IDKey2", "C:\temp\Store", "VarName1", "VarValue1", "VarName2", "VarValue2", "VarNameN", "VarValueN"

将在调用时从object[]静默强制转换为string[]