我是靠谱客的博主 激动板凳,这篇文章主要介绍C# 简单方式运行powershell文件/使用cmd命令运行ps1,现在分享给大家,希望可以做个参考。

一、目的、构想

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();
            }

        }

 

最后

以上就是激动板凳最近收集整理的关于C# 简单方式运行powershell文件/使用cmd命令运行ps1的全部内容,更多相关C#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(108)

评论列表共有 0 条评论

立即
投稿
返回
顶部