【问题标题】:How to pass parameters to a cmdlet from C#如何从 C# 将参数传递给 cmdlet
【发布时间】:2014-11-09 22:26:36
【问题描述】:

我有一些我想从 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 的正确方法是什么?

【问题讨论】:

    标签: c# powershell arguments cmdlet


    【解决方案1】:

    试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多