Search code examples
c#windowsvariablescmdinteger-arithmetic

cmd paramter set and get variables


I'm starting a cmd window with my C# code.

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

How can I declare a variable, increment it by one and then return the result all by cmd arguments?


Solution

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

    You don't even need the echo command as in command line context the set /a used for arithmetic will output the result.

    If you need the end of line after the result, then

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

    Here delayed expansion is needed (/v) to retrieve the content of the variable changed in the same line.