如何从C#传递参数到cmdlet

时间:2014-09-16 08:40:54

标签: c# powershell arguments cmdlet

我有一些我想从C#调用的powershell脚本。

从命令行我会这样做:

Import-Module c:\provisioning\newModule.psm1 –Force
Get-MTMailbox -customerID custid0001

这样可以产生正确的结果。

我想从C#调用我的脚本:

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "C:\\provisioning\\newModule.psm1" });
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("Get-MTMailbox").AddArgument("-customerID custid0001");
// Also tried this. Still ignored.
//ps.AddParameter("-customerID", "custid0001");
ps.Invoke();
Collection<PSObject> results = ps.Invoke();
foreach (PSObject psObject in results)
{
    Console.Write("Result: "+psObject.ToString());
    if (psObject.BaseObject is System.Collections.Hashtable)
    {
        Hashtable ht = (Hashtable) psObject.BaseObject;
        foreach (DictionaryEntry keypair in ht)
        {
            Console.WriteLine(keypair.Key+" "+keypair.Value); 
        }

    }
}

命令运行,但我的参数总是被忽略。

我对C#很陌生,所以也许我不知道该搜索什么。

在C#中将参数传递给cmdlet的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

ps.AddParameter("customerID", "custid0001");

您不需要-来指定参数名称