Rust allows us to run batch files in Windows using std::process::Command. These files typically have bat and cmd file extensions.
Window Batch File
Our sample batch file, named echotest.bat, contains the following MS-DOS commands. We need our Rust codes to run this file.
1 | echo Hello From echotest.bat |
Our Rust codes would look something the code snippet below.
1 2 3 4 5 6 7 8 9 10 11 12 13 | use std::process::Command; fn main() { let output = Command::new("cmd") .args(&["/C", "C:/Users/somewhere/echotest.bat"]) .output() .expect("failed to execute process"); for out in String::from_utf8(output.stdout).iter() { println!("{}", out); } } |
The /C switch tells the cmd.exe (“cmd” on line 4) to carry out the command specified by string and then terminate. Anything that follows it is processed as a command line. For more information on the switch, please use the cmd /? command on Windows Command Prompt. When we run our Rust codes, they run the batch file in the Windows file system. They can access any output using output.stdout. If we hadn’t used the /C switch, the codes wouldn’t run the second argument as a command.
1 2 | C:\Users\somewhere>echo Hello From echotest.bat Hello From echotest.bat |
The struct command is a process builder, providing fine-grained control over how Rust codes should spawn a new program in Windows. The program is typically a command-line interpreter which in this case for Windows is cmd. For Linux, it would be sh. The same codes are applicable to other environments as we specify the appropriate command-line interpreter and switches.
Tested with Rust 1.40.0 on Windows 10.