WindowsUtils class in Selenium Webdriver

WindowsUtils class provides methods to handle the process on the command prompt, with the methods present in the WindowsUtils class, we can get path details and kill the process.

WindowsUtils methods will kill only the things present on the local machine, WindowsUtils class does not have any effect on the remote machines.

WindowsUtils class is present under org.openqa.selenium.os package, all the methods present under this package are static methods. I have used WIN10 and JAVA10 for this tutorial; both are 10, funny, isn't it ?

Methods present in WindowsUtils Class

  • findSystemRoot()
  • findTaskKill()
  • getEnvVarIgnoreCase(java.lang.String var)
  • getPathsInProgramFiles(java.lang.String childPath)
  • getProgramFiles86Path()
  • getProgramFilesPath()
  • killByName(java.lang.String name)
  • killPID(java.lang.String processID)
  • loadEnvironment()
  • thisIsWindows()


We can use this method to get the root directory of the system, this method return C:/Windows path, it will be a useful couple of cases as we may need to read files from the source/root folder of the system.

import org.openqa.selenium.os.WindowsUtils;
public class AA {
	public static void main(String[] args) {


For closing, any application window command prompt calls the taskkill.exe process and which helps to close the application in the task manager.

By using findTaskKill() we can find the location of the taskkill.exe on windows.


getEnvVarIgnoreCase(java.lang.String var)

The getEnvVarIgnoreCase() method returns the environment variable set by the user, and the environment variable could be temporary or permanent. The temporary variable is nothing but the variables set using the command prompt, and permanent variables are set in Advanced system settings.



getPathsInProgramFiles() method retrieves all the paths present for a particular program; recently, you might have seen that windows have Two program files 1. Program Files, 2. Program Files (x86).

When I try to find the path for a program, for example, "java", getPathsInProgramFiles("java") method returns paths from both Program files.


getProgramFiles86Path() and getProgramFilesPath()

These method returns the path of the program files.

Complete Program fetching the system variables and paths

import org.openqa.selenium.os.WindowsUtils;
public class WindowsUtilsCherCherTech {
	public static void main(String[] args) {
		// find system root
		System.out.println("Root : "+ WindowsUtils.findSystemRoot() );
		// find taskkill.exe path
		System.out.println("taskkill.exe path : "+ WindowsUtils.findTaskKill() );
		// get environment variable
		System.out.println("Environment variable : "+ WindowsUtils.getEnvVarIgnoreCase("java_home") );
		//get program path from all program files
		System.out.println("Program path : "+ WindowsUtils.getPathsInProgramFiles("java") );
		// path of x86 system
		System.out.println("x86 : " +WindowsUtils.getProgramFiles86Path() );
		// path of the prgram files
		System.out.println("prgram files path : " +WindowsUtils.getProgramFilesPath() );


killByName(String name)

killByName method kills the task/process by its name, for example, to close the chrome browser, we can use the killByName("chrome.exe"); not only chrome, we can also terminate any application in the windows.

Have you have heard of an interview question, how will you close the Chromedriver.exe, I hope you got the answer.

Also, I hope you got the answer for, how to you close the chrome/firefox browser without using driver.close() or quit() methods.

// close the driver server
// close the chrome browser
// close firefox browser
//close the Microsoft paint

killPID(String processID)

killPID() method closes the application based on the process id; we can use this when we have the same application is opened multiple times.

Every process will have a unique PIDs.



thisIsWindows() method returns whether this machine OS is Microsoft windows or not, returns true if the machine has MS windows OS.


For handling pop related windows operations, you may need to check Robot Class and AutoIt with selenium.

Connect to Command prompt with Selenium Webdriver

We cannot connect to the command prompt in selenium webdriver, as there are no methods present in selenium to connect the command prompt.

But Java provides a method to connect to command prompt, which in terms, we can say that we can connect to command prompt with selenium webdriver.

exec() method present in Runtime class helps the user to connect to command prompt, and we have to pass the command to this method, which we want to execute in command prompt.

Runtime.getRuntime().exec("Command to run in command prompt");

Create Headless Chrome Browser in Selenium webdriver

Killing All Processes of an Application

I will discuss terminating chromedriver.exe process, but you can be terminating any program using this method.

You could always open Task Manager and kill the Chrome processes, but remember, each tab is its own process. If you have 30+ tabs open, your Task Manager will probably look like this:task-manager-windowutils
You can right-click on each process ad close it, but if there are hundreds of processes for the same applications, then this method will take hours

Windows command prompt provides a way to close handle this kind of situations, and you just need to execute below command to close all the process, below command closes all the chromedriver.exe processes.

You just need to execute this command in the command prompt, F- means kill all the process:

TASKKILL /IM chrome.exe /F

You perform the closing the processes using selenium java runtime like below, and in the place of chrome, you can use chromedriver.exe

Runtime.getRuntime().exec("TASKKILL /IM chrome.exe /F");

Read & Write Barcode using Selenium Webdriver.

Terminate the process you Opened

karthiQ I agree with you that we connect and close process using the above method, but If there is more than one chromedriver.exe is present and few chromedriver.exe (any process )invoked by other people and how come I will know which is mine.

So because of this, it will give confusion that what happens if I close someone's process or I don't want to do things without a clear solution. (See, I got power to read minds, haha)

The below section teaches how to close the process that you have opened, I know this is dry section but bear with me.

Let me put it in a simple way :
Consider you are in the below situation. You are in a team where people play a Pebble game; the game rule is this, some of your teammates will place the pebble in a sack, where already 5(assume) pebbles are present this happens while you are blindfolded.

Once he placed in the sack, they will open your blindfold; Now you got to pick the pebble that your teammate had placed.
Is it possible ?

As you never saw the pebble, the above task is impossible to pick your pebble among other pebbles ( Do not bring your probability concepts here, FYI I hate mathematics)

Will you able to the solve above puzzle if I give a clue, and the clue is I will provide the list of pebbles those are existing already ? Yes, you can get your pebble by removing the existing pebbles.

Similar to the above scenario the solution for our actual problem is : get the details of all the processes( as first) which are existing for a particular application (chromedriver.exe), Now you invoke your process and again get the details of all the processes which includes yours as well (as second) .

Now remove the first details from the second details, now what you are remaining with the process that you invoked.

Here details are nothing but the PID of the process; every process will have unique PID. An application can have multiple processes (instances) running.

Steps to Close the chromedriver.exe process invoked by you :
1. Create a class called CloseMyProcess

2. Create a method called getAllPIDs; the purpose of this method is to get all PIDs of a particular application.

3. Create an empty array list to store all the PIDs, as we do not know the number of PIDs, so we have to go for a collection that dynamically increases the size.

4. Now invoke the Cmd with a command to get all the details of the Processes

Process p = Runtime.getRuntime().exec("tasklist /FI "IMAGENAME eq chromedriver.exe*"");

5. In the above command tasklist, retrieves the all the tasks, /FI lets the user to set a filter for tasklist, "IMAGENAME eq chromedriver.exe* is nothing but IMAGENAME is process name, and eq means equals to chromedriver.exe* .

6. Now Process the stored values into BufferedReader so that we can make it as string and process it. Why, because we want to get only the PID nothing else but what we get as the output of the commands is shown in the image.


BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

7. Check whether the given input is not null, if the value is valid then assign it to a String variable called out

8. We will be using apache StringUtils to split the string with " ";

9. Now the first element will be Process name, and the second element is PID. I hope you know that the java index starts from 0. So the second element will be available at index 1

10. Add the extracted string into an ArrayList, after verifying that the item is Number (PIDs are 4-6 digit numbers)

if (items.length > 1 && StringUtils.isNumeric(items[1])) {

Main method :
11. Write a main method in the same class

12. Call the getAllPIDs to have a track of the existing process

List<String> beforePIDS = getAllPIDs();

13. Set system property and open chrome browser

14. Call the getAllPIDs to get all the process of the current time; now, this list will have the process that we have invoked.

15. Now remove the existing list (step 12) from the current list (step 14), so we will have only the process that we have invoked.


16. Now our process is only thing that will be remaining in the list(at index 0), now get PID.

17. Terminate the process using PID with the help of killPID() method.

18. You can verify whether we have closed out process only or not by getting details from the getAllPIDs method.


Complete program for terminating out chromedriver.exe

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.os.WindowsUtils;
public class AA {
	public static String pid_We_Invoked;
	public static void main(String[] args) throws IOException {
		List<String> beforePIDS = getAllPIDs();
		System.out.println("Before invoking our PID : " + beforePIDS);
		System.setProperty("", "D:PATHchromedriver.exe");
		WebDriver driver = new ChromeDriver();
		List<String> afterPIDs = getAllPIDs();
		System.out.println("After invoking our PID : " + afterPIDs);
		pid_We_Invoked = afterPIDs.get(0);
		System.out.println("Our PID ** : "+pid_We_Invoked);
		// kill the process based o PID

		List<String> remainingPIDS = getAllPIDs();
		System.out.println("After terminating our PID : " + remainingPIDS);

	public static List getAllPIDs() throws IOException {
		List<String> pids = new ArrayList<String>();
		String out;
		Process p = Runtime.getRuntime().exec("tasklist /FI "IMAGENAME eq chromedriver.exe*"");
		BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while ((out = input.readLine()) != null) {
			String[] items = StringUtils.split(out, " ");
			if (items.length > 1 && StringUtils.isNumeric(items[1])) {
		return pids;

The output of Terminating chromedriver.exe invoked by your


How to handle two Browser Windows in Selenium

Zip File Handling in selenium

Zip class present in selenium helps the user to perform zipping and unzipping operations; these kinds of operation will be helpful when you want to download files and verify its contents.

Zip class present under package in selenium webdriver

zip method in selenium

zip() method present Zip class helps us to zip a file, into .zip format. File(""));

unZip method in selenium

unZip method extracts the content of the zip file into a specific folder.

To use this method, we need to pass two parameters, 1. Which file we want to unzip, 2. Where we should store the unzipped files.

FileInputStream fis = new FileInputStream("");
Zip.unzip(fis, new File("C:UsersuserDesktopip"));

Xpath in Selenium

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • suhi
    Hi Karthiq,
    I have an excel file which needs to be closed before I do write operation. I am using following command
    Runtime.getRuntime().exec("taskkill /FI "WindowTitle eq Output.xlsx - Excel");
    The above works well if it is active or focused on. However If there are more than one excel instance with (different file names) the script doesn't close the output file. 
    I could kill whole excel.exe but that would kill all excel files which I don't want.
    Can you please suggest me how to kill a specific excel file ?
    In the task manager if we see there is only 1 PID for EXCEL.EXE. 
  • kauser
    can we use zipfunction to check if a single downloaded file(pdf) exists?..
    the scenario is i hav to download a pdf report..and verify if the file exists.. the file is gtg stored in
    1. i have to store file in project directory
    2. i have to verify pdf downloaded..the file name is always random..
    • karthiq [admin]
      Hi Kauser,
      I didnot get whole problem but I am giving below based on my Understanding of your problem.
      1. You have to set the MiMe type and path or Just know where your browser stores your downloaded files.
      2. I am considering your pdf file is present inside a zip file. Once you extract the zip file use normal File operations using File Class, so get pdf files using a filter pdf.
      I am pasting the code, which filters pdf but make changes according to your need.
      import java.util.ArrayList;
      import java.util.List;
      public class AccordianHeader {
      	public static String path = "C:\Users\user\Music\site\java";
      	public static void main(String[] args) throws IOException {
      		for (File file : getAllFiles()) {
      			FileInputStream fis = new FileInputStream(file.getCanonicalPath());
      			byte[] buffer = new byte[10];
      			StringBuilder sb = new StringBuilder();
      			while ( != -1) {
      				sb.append(new String(buffer));
      				buffer = new byte[10];
      	public static List getAllFiles(){
      		List lis = new ArrayList<>();
      		for (File file : getPHPFiles(path)) {
      		return lis;
      	public static File[] getPHPFiles(String dirName){
      		File dir = new File(dirName);
              return dir.listFiles(new FilenameFilter() { 
                       public boolean accept(File dir, String filename)
                            { return filename.endsWith(".pdf"); }
              } );
      • farnaaz
        my apologies..maybe i dint explain the scenario properly. I am working on an automation project..using Page object model/MAVEN. In the application, i have to click a button which will generate/download a pdf report. The report is getting downloaded on my C:/ drive. so if the code is run on any other device my test case will fail.. 
        so, i need to change the location of my downloaded pdf from C:/ drive to my maven project directory..It is just a single pdf file not a zip file.. can you advise how to get that pdf location changed ? thanks 
  • Pavankumar
    Java menu moved lite to right