簡體   English   中英

如何從C#將參數傳遞給cmdlet

[英]How to pass parameters to a cmdlet from C#

我有一些要從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的正確方法是什么?

試試這個:

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

您不需要-來指定參數名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM