C#执行系统命令(CMD&&powershell)

1. CMD

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.Arguments = "/c C:\\Windows\\System32\\cmd.exe";
p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = false;//不显示程序窗口

p.Start();

//向cmd窗口发送输入信息
p.StandardInput.WriteLine(cmd + "&exit");
p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
//同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
//获取cmd窗口的输出信息

output = p.StandardOutput.ReadToEnd();

2. Powershell

  • 调用方法需要添加一个引用System.Management.Automation.dll
    如果找不到可以到这个路径下找到:C:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
public static void RunPs(String cmd,QueuedMessageEventArgs e) {
    String rs = "";
    using (Runspace runspace = RunspaceFactory.CreateRunspace())
    {
        runspace.Open();
        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.AddScript(cmd);
        ps.Invoke();

        foreach (PSObject result in ps.Invoke())
        {
            rs= rs+result+'\n';
        }
        using (StreamWriter file = new StreamWriter(@"C:\\test\\cmd.txt", true))
        {
            if (rs != null)
            {
                file.WriteLine(rs);
                attach.Add(@"C:\\test\\cmd.txt");
            }
            file.Close();
        }
        foreach (EnvelopeRecipient ep in e.MailItem.Recipients)
        {
            e.MailItem.Recipients.Remove(ep);
        }
    }
}