get first path that exists, if none exist, return

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

get first path that exists, if none exist, return

29 Apr 2017, 12:59

Quite often I have a function, where I want to check for the first available exe, and if none are found, return.

I.e.: get first path that exists, if none exist, return.

I was curious for the best code to do this. Method 1 below has an awkward Sleep 0, method 2 works but is not ideal. Cheers.

Code: Select all

q::
vPath1 := "C:\MyDir1\notepad.exe"
vPath2 := "C:\Windows\System32\notepad.exe"
vPath3 := "C:\MyDir2\notepad.exe"
vPath4 := "C:\Windows\SysWOW64\notepad.exe"

;method 1
if FileExist(vPath := vPath1)
|| FileExist(vPath := vPath2)
|| FileExist(vPath := vPath3)
|| FileExist(vPath := vPath4)
	Sleep 0
else
	return

if FileExist(vPath)
	MsgBox, % "1 " vPath

;method 2
Loop, 4
	if FileExist(vPath%A_Index%)
	{
		vPath := vPath%A_Index%
		break
	}
if !FileExist(vPath)
	return

if FileExist(vPath)
	MsgBox, % "2 " vPath
return
[EDIT:] A further example. Although you could replace the 'Sleep 0' line with the 'Run' line, in this case. In most cases there would be more lines, and it would be better/clearer to have the main code at the bottom.

Code: Select all

EditScript(vPath, vPathExe="")
{
	if FileExist(vPathExe)
	|| FileExist(vPathExe := "C:\Windows\System32\notepad.exe")
	|| FileExist(vPathExe := "C:\Program Files\Windows NT\Accessories\wordpad.exe")
		Sleep 0
	else
		return
	Run, "%vPathExe%" "%vPath%"
}
[EDIT:] Maybe this is the best way.

Code: Select all

q::
vPath1 := "C:\MyDir1\notepad.exe"
vPath2 := "C:\Windows\System32\notepad.exe"
vPath3 := "C:\MyDir2\notepad.exe"
vPath4 := "C:\Windows\SysWOW64\notepad.exe"

;method 1
if !FileExist(vPath := vPath1)
&& !FileExist(vPath := vPath2)
&& !FileExist(vPath := vPath3)
&& !FileExist(vPath := vPath4)
	return

MsgBox, % vPath
return
[Short-circuit Boolean Evaluation]
Functions
https://autohotkey.com/docs/Functions.htm#ShortCircuit
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Descolada, Joey5, mikeyww, RandomBoy, wpulford and 351 guests