Rust, Software Development

How To Windows Batch Files Using Rust

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.

Our Rust codes would look something the code snippet below.

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.

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.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like