cmd参数设置并获取变量

时间:2015-10-29 12:27:20

标签: c# windows variables cmd integer-arithmetic

我用C#代码启动cmd窗口。

string cmd = "/c echo test";
System.Diagnostics.Process process2 = new System.Diagnostics.Process();
process2.StartInfo.FileName = "cmd.exe";
process2.StartInfo.Arguments = cmd;
process2.StartInfo.CreateNoWindow = true;
process2.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process2.StartInfo.UseShellExecute = false;
process2.StartInfo.RedirectStandardOutput = true;
process2.Start();

string output2 = process2.StandardOutput.ReadToEnd();
MessageBox.Show(output2);

如何声明变量,将其递增1,然后通过cmd参数返回结果?

1 个答案:

答案 0 :(得分:1)

cmd /c "set x=0 & set /a x+1"

在命令行上下文中甚至不需要echo命令,用于算术的set /a将输出结果。

如果您需要结果后面的行尾,那么

cmd /v /c "set x=0 & >nul set /a x+=1 & echo !x!"

此处需要延迟扩展(/v)以检索在同一行中更改的变量的内容。