public static void InvokeSystemPS(string cmd)
{
List<string> ps = new List<string>();
ps.Add("Set-ExecutionPolicy RemoteSigned");
ps.Add("Set-ExecutionPolicy -ExecutionPolicy Unrestricted");
ps.Add("& " + cmd);
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
foreach (var scr in ps)
{
pipeline.Commands.AddScript(scr);
}
pipeline.Invoke();//Execute the ps script
runspace.Close();
}
PowerShell应为编写和运行都很方便,所以为了重复利用,经常写了一些小方法或者PS代码片段。使用的时候可能会很难找到自己想要的那个方法,如果要是有一个界面把这些代码管理起来并且调用,那就很爽了

.创建一个powershell的方法,供C#调用,方法很简单,两个数的加法运算

function Sum

{

param([int]$first, [int]$second)

$result = $first + $second

return $result

}

 . 在C#的控制台程序中创建一个私有方法,调用powershell

首先定义一个powershell存放路径的全局变量

private static string script =File.ReadAllText(@"Path\Sum.ps1");

        private static void CallPS1()

        {

            using (Runspace runspace = RunspaceFactory.CreateRunspace())

            {

                runspace.Open();

                PowerShell ps = PowerShell.Create();

                ps.Runspace = runspace;

                ps.AddScript(script);

                ps.Invoke();

                ps.AddCommand("Sum").AddParameters(

                    new Dictionary<string, int>()

                    {

                        {"first", },

                        {"second", }

                    }

                    );

                foreach (PSObject result in ps.Invoke())

                {

                    Console.WriteLine("CallPS1()");

                    Console.WriteLine(result);

                }

            }

        }

调用方法需要添加一个引用System.Management.Automation.dll 
powershell命令行找System.Management.Automation.dll命令 : [psobject].Assembly.Location

最新文章

  1. 玩转spring boot——快速开始
  2. bash/shell编程学习(3)
  3. AC日记——行程长度编码 openjudge 1.7 32
  4. phonegap android3.5.1 Crosswalk
  5. DateTable与List&lt;T&gt;相互转换 及JSON与DataTable(DataSet)相互转化
  6. 马上着手开发Mac应用程序
  7. python爬虫数据抓取方法汇总
  8. Qt 打包发布 不能动态打开图片显示问题
  9. sql分组合并字段重复项sql for xml path
  10. HighCharts之2D柱状图、折线图的组合双轴图
  11. 如何在Cocos2D游戏中实现A*寻路算法(五)
  12. Fusion Log
  13. 编译u-boot问题总结
  14. delphi 中出现dataset not in edit or insert mode的问题
  15. Ubuntu12.04系统复制速度奇慢的原因猜想
  16. InnoDB存储引擎介绍-(6) 一. Innodb Antelope 和Barracuda区别
  17. oracle create tablespace
  18. Oracle性能优化2- 依据场景选择技术
  19. 2018.11.07 NOIP模拟 分糖果(贪心)
  20. 基于S3C2440的嵌入式Linux驱动——看门狗(watchdog)驱动解读

热门文章

  1. unity, multi pass shader中的surface pass
  2. js中的前绑定和后绑定详解
  3. [100]linux输入输出重定向
  4. 【Android】4.1 UI设计器
  5. angular学习笔记(十四)-$watch(1)
  6. vue 阅读一【待完结】
  7. 不同版本Lua介绍
  8. TagsView.vue
  9. 【JavaFx】客户端服务器C/S架构搭建
  10. c++之---初探重载操作符