设为首页 加入收藏

TOP

How to launche powershell script in C#
2015-11-21 01:03:54 来源: 作者: 【 】 浏览:2
Tags:How launche powershell script

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

?

?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 1452 Happy 2004 (因子和) 下一篇ZOJ 3872 Beauty of Array(数学)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: