一、目的、构想
1.C# winfrom编译的tool 运行一个powershell文件。
2.只需要运行即可,不需要返回值。
3.网上部分资料需要额外添加dll。
3.已经有cmd执行命令的函数,能否直接在cmd运行?
4.在cmd黑色窗口输入powershell 能进入powershell。
二、code实现
因为系统会默认禁止执行外部ps1文件,需要设置。
//设置执行策略
string cmd = "powershell Set-ExecutionPolicy RemoteSigned";
CommonLib.RunCMDcommand(cmd, localCreateGroupFolder);
//设置执行策略
cmd = "powershell Set-ExecutionPolicy -ExecutionPolicy Unrestricted";
CommonLib.RunCMDcommand(cmd, localCreateGroupFolder);
// 执行ps1文档
cmd = "powershell " + excuteCreateGroup;
CommonLib.RunCMDcommand(cmd, localCreateGroupFolder); public static void RunCMDcommand(string command, string workingDirectory)
{
using (Process pc = new Process())
{
pc.StartInfo.FileName = "cmd.exe";
pc.StartInfo.CreateNoWindow = false;//隐藏窗口运行
pc.StartInfo.RedirectStandardError = true;//重定向错误流
pc.StartInfo.RedirectStandardInput = true;//重定向输入流
pc.StartInfo.RedirectStandardOutput = true;//重定向输出流
pc.StartInfo.UseShellExecute = false;
pc.StartInfo.WorkingDirectory = workingDirectory;
pc.Start();
//输入CMD命令
pc.StandardInput.WriteLine(command);
pc.StandardInput.WriteLine("exit");//结束执行,很重要的
pc.StandardInput.AutoFlush = true;
//outPut = pc.StandardOutput.ReadToEnd();//读取结果 //注释可能继续跑,app不会等待卡死
pc.WaitForExit();
pc.Close();
}
}
版权声明:本文为winterye12原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。