invoke a powershell script with parameters in csharp

You can invoke a PowerShell script with parameters in C# using the Process class. Here's an example code block that demonstrates how to do it:

main.cs
using System.Diagnostics;

// ...

string scriptPath = "path/to/script.ps1";
string scriptArgs = "-param1 value1 -param2 value2";

ProcessStartInfo processInfo = new ProcessStartInfo("powershell.exe", $"-File {scriptPath} {scriptArgs}");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;

Process process = new Process();
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
417 chars
16 lines

In the example above, you need to set the scriptPath variable to the path of your PowerShell script file and set the scriptArgs variable to the command line arguments you want to pass to the script.

Then, you can create a new ProcessStartInfo object and set its FileName property to "powershell.exe" and its Arguments property to "-File {scriptPath} {scriptArgs}". This tells the Process class to start a new PowerShell process and run the script file located at scriptPath, passing the arguments specified in scriptArgs.

Finally, you start the Process object and wait for it to exit using process.WaitForExit(). This will ensure that the script finishes executing before your C# code continues.

gistlibby LogSnag