[Window PowerShell05]-C# 调用PowerShell脚本

       C# 和 PowerShell都是基于.net 平台面向对象的语言,由于PowerShell脚本功能强大,对于复制删除文件,管理进程和服务,读取EventLog,操作注册表等任务,PowerShell做起来很容易,我们可以将这些内容封装在PowerShell脚本中,C#代码仅做工作流的事情,这样发挥了脚本高效性的优势,脚本重用性强(可以使用Invoke运行在远程服务器上),而且修改简单。所以,使用C# 和脚本结合的方式是一种理想的组合。

       下面介绍一个简单的例子,说明C# 如何调用PowerShell脚本。

        private static string GetFileContent(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            StreamReader reader = new StreamReader(fs);
            return reader.ReadToEnd();
        }

        private static string RunScript(string filePath)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();
            // open it
            runspace.Open();
            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            string scriptText = GetFileContent(filePath);

            pipeline.Commands.AddScript(scriptText);
            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            //pipeline.Commands.Add("Out-String");
            // execute the script
            System.Collections.ObjectModel.Collection<PSObject> results = pipeline.Invoke();
            // close the runspace
            runspace.Close();
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
        }

        static void Main(string[] args)
        {
            string filePath = "1.ps1";
            RunScript(filePath);
            Console.ReadKey();
        }

         不仅如此,可以通过C# 给脚本传参数,下一篇会介绍。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值