程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> How to launche powershell script in C#

How to launche powershell script in C#

編輯:關於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!

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved