简体   繁体   中英

How to pass powershell parameters in c#

I'm trying to pass powershell parameters using c#. How can I pass these parameters in c# so that it will execute as expected. The function is Update-All which passes the variable Name that is 'test example'. The command that I will like to invoke is to call the function to Disable that variable Name 'test example.' Thanks in Advance.

    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();

    }

Is this okay? The answer is similar to this post

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());
}

The results/errors will be printed in the string builder for you to see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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