首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c#中传递powershell参数

如何在c#中传递powershell参数
EN

Stack Overflow用户
提问于 2019-10-22 23:52:49
回答 1查看 164关注 0票数 0

我正在尝试使用c#传递powershell参数。我如何在c#中传递这些参数,这样它才能按预期执行。这个函数是Update-All,它传递的变量名是'test example‘。我想调用的命令是调用函数来禁用名为'test example.‘的变量。提前谢谢。

代码语言:javascript
复制
    protected void Page_Load(object sender, EventArgs e)
    {
        TestMethod();
    }

    string scriptfile = "C:\\Users\\Desktop\\Test_Functions.ps1";

    private Collection<PSObject> results;

    public void TestMethod()
    {
        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

        Pipeline pipeline = runspace.CreatePipeline();

        //Here's how you add a new script with arguments
        Command myCommand = new Command(scriptfile);

        CommandParameter testParam = new CommandParameter("Update-All Name 'test example'", "Function 'Disable'");
        myCommand.Parameters.Add(testParam);

        pipeline.Commands.Add(myCommand);

        // Execute PowerShell script
        results = pipeline.Invoke();

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-23 00:02:25

这样可以吗?答案类似于此post

代码语言:javascript
复制
public void TestMethod()
{
    string script = @"C:\Users\Desktop\Test_Functions.ps1";

    StringBuilder sb = new StringBuilder();

    PowerShell psExec = PowerShell.Create();
    psExec.AddScript(script);
    psExec.AddCommand("Update-All Name 'test example'", "Function 'Disable'");

    Collection<PSObject> results;
    Collection<ErrorRecord> errors;
    results = psExec.Invoke();
    errors = psExec.Streams.Error.ReadAll();

    if (errors.Count > 0)
    {
        foreach (ErrorRecord error in errors)
        {
            sb.AppendLine(error.ToString());
        }
    }
    else
    {
        foreach (PSObject result in results)
        {
            sb.AppendLine(result.ToString());
        }
    }

    Console.WriteLine(sb.ToString());
}

结果/错误将在字符串构建器中打印出来,供您查看

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58508054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档