How to launche powershell script in C #

Source: Internet
Author: User

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 cocould 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!

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.