Search code examples
javawindowscmdcommand-promptprocessbuilder

Running Windows Scanner in command prompt for a file From Java


I am trying to scan a file programmatically from Java and want to do it on the command line.

I have this working directly in the command line (simple navigate to folder and execute command:

c:\Users\3XXXXX8\Desktop>cd "C:\\Program Files\\Windows Defender" && MpCmdRun.exe -Scan -ScanType 3 -File "C:\\UploadedFiles\\file"
Scan starting...
Scan finished.
Scanning C:\\UploadedFiles\\file found no threats.

I want it to work from Java. I am confused about The string that I should feed the Process. I have found some places that I should feed in the command strings with a \c because it is widows. But that doesn't work. Program is as follows. The String [] commands needs to be fixed.

import java.io.*;

    public class CmdTest {
        public static void main(String[] args) throws Exception {
            String [] commands = {
                "cmd /c \"cd \"C:\\Program Files\\Windows Defender\" && MpCmdRun.exe -Scan -ScanType 3 -File \"C:\\UploadedFiles\\file\"\""
            }
            ProcessBuilder builder = new ProcessBuilder(commands);
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ( (line = r.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

Please help.

Some other combinations that I have tried for the command string:

String [] commands = { "cmd.exe", "/c", "cd \"C:\\Program Files\\Windows Security Client\"",
                    "MpCmdRun.exe -Scan -ScanType 3 -File C:\\UploadedFiles\\" + file.getName()
            };

and

String [] commands = {
            "cmd /c \"cd \"C:\\Program Files\\Windows Defender\" && MpCmdRun.exe -Scan -ScanType 3 -File \"C:\\UploadedFiles\\file\"\""
        }


String [] commands = {
                "cmd \"cd \"C:\\Program Files\\Windows Defender\" && MpCmdRun.exe -Scan -ScanType 3 -File \"C:\\UploadedFiles\\file\"\""
            }

Not sure how to break it up.


Solution

  • String [] commands = {
                "\"C:\\Program Files\\Windows Defender\\MpCmdRun.exe\" -Scan -ScanType 3 -File \"C:\\UploadedFiles\\file\""
            };
    

    This worked for me ^.

    I did not need the "cmd /c"