invoke a powershell script with parameters with user access in csharp

You can use the PowerShell class available in the Microsoft.PowerShell.Commands.Management namespace to invoke a PowerShell script with parameters from a C# application. Here's an example:

main.cs
using System;
using System.Management.Automation;

namespace PowerShellExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new PowerShell object
            PowerShell ps = PowerShell.Create();

            // Add the script file to the PowerShell object
            ps.AddScript(@"C:\Scripts\MyScript.ps1");

            // Add parameters to the script
            ps.AddParameter("Param1", "Value1");
            ps.AddParameter("Param2", "Value2");

            // Set the execution policy to allow scripts to run
            ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "Unrestricted").AddParameter("Scope", "Process");

            // Invoke the script and wait for it to finish
            ps.Invoke();

            // Check for any errors or output from the script
            foreach (var error in ps.Streams.Error)
            {
                Console.WriteLine("Error: " + error.ToString());
            }
            foreach (var output in ps.Streams.Output)
            {
                Console.WriteLine("Output: " + output.ToString());
            }
        }
    }
}
1164 chars
38 lines

In the example above, replace C:\Scripts\MyScript.ps1 with the path to your PowerShell script file, and Param1, Value1, Param2, and Value2 with your actual script parameters. Make sure to set the execution policy to Unrestricted so that the script can run.

Note that the above example runs the script with the current user's permissions. If you need to run the script with elevated permissions, you will need to launch the C# application as an administrator.

gistlibby LogSnag