/**By Dylan SUN**/
If you want to launch a powershell script in CSharp application, you don't necessarily need to construct a cmd command line to launch the script.
You could make your life easier with following example:
Variable "script" is the full path of the powershell script
Variable "parameters" is an instance of type of IDictionary, which contains a bunch of parameter key/values.
using (var powerShellInstance = PowerShell.Create()) { //Prepare powershell execution powerShellInstance.AddCommand(script); powerShellInstance.AddParameters(parameters); //Execute powershell command and get the results var results = powerShellInstance.Invoke(); var errors = powerShellInstance.Streams.Error; var sb = new StringBuilder(); if (errors.Count > 0) { foreach (var error in errors) { sb.Append(error); } errorResult = sb.ToString(); } else { foreach (var result in results) { sb.AppendLine(result.ToString()); } executionResult = sb.ToString(); } return errors.Count == 0; }
I hope you find this article helpful!