如何使用C#轻松运行Shell命令?

发布于 2024-12-05 07:12:32 字数 367 浏览 1 评论 0原文

如何使用C#运行命令提示命令? 假设我想按顺序运行这些命令:

cd F:/File/File2/...FileX/
ipconfig
ping google.com

或类似的东西...有人可以做到此方法:

void runCommands(String[] commands) 
{
    //method guts...
}

使您的输入是一系列字符串命令(即[“ ipconfig”,“ ping 192.168.192.168”,“ ping google.com“,“ nslookup facebook.com”)应在将其放入数组中的特定顺序中以单个命令提示进行执行。谢谢。

how do i use c# to run command prompt commands?
Lets say i want to run these commands in a sequence:

cd F:/File/File2/...FileX/
ipconfig
ping google.com

or something like that...Can someone make this method:

void runCommands(String[] commands) 
{
    //method guts...
}

such that your input is a series of string commands (i.e ["ipconfig","ping 192.168.192.168","ping google.com","nslookup facebook.com") that should be executed on a single command prompt in the specific sequence in which they are put in the array. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

三五鸿雁 2024-12-12 07:12:32

应该在特定的单个命令提示符下执行
它们放入数组的顺序

您可以在 bat 文件中编写命令序列并按如下方式运行。

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

参考

that should be executed on a single command prompt in the specific
sequence in which they are put in the array

You could write command sequence in a bat file and run as below.

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Reference

她如夕阳 2024-12-12 07:12:32

为此我编写了一个动态类Shell。您可以像这样使用它:

var shell = new Shell();

shell.Notepad("readme.txt"); // for "notepad.exe readme.txt"
shell.Git("push", "http://myserver.com"); // for "git push http://myserver.com"
shell.Ps("ls"); // for executing "ls" in powershell;
shell.Instance; // The powershell instance of this shell.

这是该类(它使用 System.Automation nuget 包来实现 powershell 功能):

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Management.Automation;

namespace System.Diagnostics {

    public class Shell : System.Dynamic.DynamicObject {

        public Shell(): base() { }
        public Shell(bool window) { Window = window; }

        static string[] ScriptExtensions = new string[] { ".exe", ".cmd", ".bat", ".ps1", ".csx", ".vbs" };

        public string Path { get { return Environment.GetEnvironmentVariable("PATH"); } set { Environment.SetEnvironmentVariable("PATH", value); } }

        PowerShell pshell = null;

        public PowerShell Instance { get { return pshell ?? pshell = PowerShell.Create(); } }

        public bool Window { get; set; }

        public ICollection<PSObject> Ps(string cmd) {
            Instance.AddScript(cmd);
            return Instance.Invoke();
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {

            var exe = Path.Split(';').SelectMany(p => ScriptExtensions.Select(ext => binder.Name + ext)).FirstOrDefault(p => File.Exists(p));

            if (exe == null) exe = binder.Name + ".exe";

            var info = new ProcessStartInfo(exe);
            var sb = new StringBuilder();
            foreach (var arg in args) {
                var t = arg.ToString();
                if (sb.Length > 0) sb.Append(' ');
                if (t.Contains(' ')) { sb.Append('"'); sb.Append(t); sb.Append('"'); } else sb.Append(t);
            }
            info.Arguments = sb.ToString();
            info.CreateNoWindow = !Window;
            info.UseShellExecute = false;
            info.WindowStyle = Window ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
            try {
                var p = Process.Start(info);
                p.WaitForExit();
                result = p.ExitCode;
                return true;
            } catch {
                result = null;
                return false;
            }
        }

    }
}

I wrote a dynamic class Shell for this purpose. You can use it like so:

var shell = new Shell();

shell.Notepad("readme.txt"); // for "notepad.exe readme.txt"
shell.Git("push", "http://myserver.com"); // for "git push http://myserver.com"
shell.Ps("ls"); // for executing "ls" in powershell;
shell.Instance; // The powershell instance of this shell.

Here's the class (It uses the System.Automation nuget package for powershell features):

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Management.Automation;

namespace System.Diagnostics {

    public class Shell : System.Dynamic.DynamicObject {

        public Shell(): base() { }
        public Shell(bool window) { Window = window; }

        static string[] ScriptExtensions = new string[] { ".exe", ".cmd", ".bat", ".ps1", ".csx", ".vbs" };

        public string Path { get { return Environment.GetEnvironmentVariable("PATH"); } set { Environment.SetEnvironmentVariable("PATH", value); } }

        PowerShell pshell = null;

        public PowerShell Instance { get { return pshell ?? pshell = PowerShell.Create(); } }

        public bool Window { get; set; }

        public ICollection<PSObject> Ps(string cmd) {
            Instance.AddScript(cmd);
            return Instance.Invoke();
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {

            var exe = Path.Split(';').SelectMany(p => ScriptExtensions.Select(ext => binder.Name + ext)).FirstOrDefault(p => File.Exists(p));

            if (exe == null) exe = binder.Name + ".exe";

            var info = new ProcessStartInfo(exe);
            var sb = new StringBuilder();
            foreach (var arg in args) {
                var t = arg.ToString();
                if (sb.Length > 0) sb.Append(' ');
                if (t.Contains(' ')) { sb.Append('"'); sb.Append(t); sb.Append('"'); } else sb.Append(t);
            }
            info.Arguments = sb.ToString();
            info.CreateNoWindow = !Window;
            info.UseShellExecute = false;
            info.WindowStyle = Window ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
            try {
                var p = Process.Start(info);
                p.WaitForExit();
                result = p.ExitCode;
                return true;
            } catch {
                result = null;
                return false;
            }
        }

    }
}
坏尐絯℡ 2024-12-12 07:12:32

我不会为你填补空白(鱼),而是给你鱼竿:
http://msdn.microsoft.com/en-us/library /system.diagnostics.process.aspx

查看 Process 类。

I won't fill the blank (fish) for you but instead give you the rod:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Check out the Process class.

信仰 2024-12-12 07:12:32

您应该使用 .Net 等效项,可以在 System.IOSystem.Net 中找到。

You should use the .Net equivalents, which can be found in System.IO and System.Net.

最丧也最甜 2024-12-12 07:12:32

你想做什么?如果您正在考虑进行脚本并使用.NET框架,请查看

您可以在Powerhsell脚本中使用所有提到的命令 - CD,IPCONFIG,NSLOEGUP,PING等。

What are you trying to do? If you are looking at doing scripting and also use the .Net framework, have a look at Powershell

You can use all the commands that you mention as such in Powerhsell scripts - cd, ipconfig, nslookup, ping etc.

爱格式化 2024-12-12 07:12:32

在这里您可以找到运行 shell 命令的解决方案源代码...它甚至考虑了 stderr。

但正如 @SLaks 指出的那样:是使用 .NET Framework 执行您所描述的操作的更好方法(即 System.IOSystem.Net)!

其他有趣的资源:

Here you can find a solution for running shell commands complete with source code... it even takes stderr into account.

BUT as @SLaks pointed out: there are better ways to do what you describe by using the .NET Framework (i.e. System.IO and System.Net)!

Other interesting resources:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文