As an extension to @Minor's answer, if you wanted to increase performance by limiting search to only programs that are currently "installed" on Windows, the following registry keys contain information on "installed" programs.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
Using powershell, you can access properties of installed software stored in these keys. Of particular interest is the InstallLocation
property.
Then, you just modify your Java code to utilise another batch script that retrieves these install locations, and specifically target these install locations for exe
files.
getInstalledPrograms.bat
@echo off
powershell -Command "Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match \"%1\"} | Select-Object -Property InstallLocation"
exit
getPrograms.bat
@echo off
cd %1
dir /b /s "*%2*.exe"
exit
Java Example:
String search = "skype";
try {
Process getInstalled = Runtime.getRuntime().exec("./src/getInstalledPrograms.bat " + search);
BufferedReader installed = new BufferedReader(new InputStreamReader(getInstalled.getInputStream()));
String install;
String exe;
int count = 0;
while(true) {
install = installed.readLine();
if(install == null) {
break;
}
install = install.trim();
// Ignore powershell table header and newlines.
if(count < 3 || install.equals("")) {
count++;
continue;
}
Process getExes = Runtime.getRuntime().exec("./src/getPrograms.bat " + "\"" + install + "\"");
BufferedReader exes = new BufferedReader(new InputStreamReader(getExes.getInputStream()));
while(true) {
exe = exes.readLine();
if(exe == null) {
break;
}
exe = exe.trim();
System.out.println(exe);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Currently my Java example duplicates InstallLocation
returned by getInstalledPrograms.bat, although the script works fine in cmd. Conceptually though, this solution is sound.