简体   繁体   English

如何从C#将参数传递给cmdlet

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

I have some powershell scripts that I want to call from C#. 我有一些要从C#调用的powershell脚本。

From the commandline I would do this: 在命令行中,我将执行以下操作:

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

This works and gives the correct result. 这可以工作并给出正确的结果。

I want to call my scripts from C#: 我想从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); 
        }

    }
}

The command runs, but my arguments are always ignored. 该命令运行,但始终忽略我的参数。

I'm very new to C# so maybe I don't know what to search for. 我是C#的新手,所以也许我不知道要搜索什么。

What's the correct way to pass arguments to a cmdlet in C#? 在C#中将参数传递给cmdlet的正确方法是什么?

try with this: 试试这个:

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

You do not need the - to specify the argument name 您不需要-来指定参数名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM