执行CMD时参数不工作

本文关键字:工作 参数 CMD 执行 | 更新日期: 2023-09-27 18:15:23

我试图执行这个CMD命令来改变我的DNS,但它不工作。我没有得到任何错误。它要求以管理员身份运行,但它不工作。

如果我手动在CMD中输入参数,它会工作。

下面是我的代码:
System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); 
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"'System32'cmd.exe";
myProcessInfo.Arguments = "set DNS1=198.168.97.1 " +
    "set DNS2=5.2.2.2 " +
    "set DNS3=206.19.29.17 " +
    "set INTERFACE=Ethernet " +
    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no " +
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 " +
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3" +
    "ipconfig /flushdns";
myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
myProcessInfo.Verb = "runas"; 
System.Diagnostics.Process.Start(myProcessInfo);

执行CMD时参数不工作

实际上您所做的是将所有命令附加为普通参数。要么为每个命令运行命令行,要么在命令之间添加&符号以链接它们。另外,您需要使用/c -参数来传递命令。所以你的代码看起来像这样:

myProcessInfo.Arguments = "/c 'set DNS1=198.168.97.1 && " +
                                    "set DNS2=5.2.2.2 && " +
                                    "set DNS3=206.19.29.17 && " +
                                    "set INTERFACE=Ethernet && " +
                                    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no && " +
                                    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 && " +
                                    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3 && " +
                                    "ipconfig /flushdns'";

可能是这样的:

var tempFileName = Path.GetTempFileName() + ".cmd";
File.WriteAllLines(tempFileName, new[]
{
    "set DNS1=198.168.97.1 ", 
    "set DNS2=5.2.2.2 ",
    "set DNS3=206.19.29.17 ",
    "set INTERFACE=Ethernet ",
    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no ",
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 ",
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3",
    "ipconfig /flushdns"
});
var myProcessInfo = new ProcessStartInfo();
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") 
    + @"'System32'cmd.exe /C " + tempFileName;
myProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcessInfo.Verb = "runas";
var myProcess = Process.Start(myProcessInfo);
if (myProcess != null)
    while (!myProcess.HasExited)
    {
        myProcess.Refresh();
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
File.Delete(tempFileName);