当前位置: 代码迷 >> C# >> How to launche powershell script in C
  详细解决方案

How to launche powershell script in C

热度:260   发布时间:2016-05-05 04:02:42.0
How to launche powershell script in C#

/**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!



  相关解决方案