Windows – Batch file – How to run an .exe file with a randomized name

batchbatch filewindows 10

I'm trying to make a batch file run a .exe file after I've downloaded it. The problem is, the name of the downloaded file is randomized upon download (done so from the webpage it's downloaded from). I have no way of guessing the name of the file, so I want the batch file to run the .exe file regardless of what name it may have.

I want it to:

1: download the file – which it does perfectly.

2: then run the .exe file regardless of the name – which doesn't work as intended. (Error; Windows cannot find '*.exe'. Make sure you've typed the name correctly, then try again) – I have tried several solutions provided around the web from a mashup of questions – nothing works.

3: delete the file – which it does perfectly.

This is what I got so far:

echo Downloading file...
start "" https://TheWebPagesName.com
PING localhost -n 10 >NUL
echo Running file...
start "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername\*.exe"
PING localhost -n 10 >NUL
echo Deleting File...
del "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername\*.exe"
PING localhost -n 2 >NUL
echo Done!
PING localhost -n 6 >NUL
echo Exiting...
PING localhost -n 4 >NUL

Any suggestions?

Best Answer

You can accomplish this by using forfiles.

Forfiles can search for files, and then execute a command and use the files it finds as a variable, or do some checks. Forfiles supports filemasks, and given that you explained that the exefile is the only file in the folder, forfiles can be used.

Your script would look like this:

echo Downloading file...
start "" https://TheWebPagesName.com
PING localhost -n 10 >NUL
echo Running file...

:: comment out old row for easy reading    
:: start "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername\*.exe"

:: insert new comamnd instead:
forfiles /p "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername" /m *.exe /c "@file"

:: if you were not using executables, but would want to use start file.txt, you would use:
::forfiles /p "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername" /m *.txt /c "cmd /c @file"

PING localhost -n 10 >NUL
echo Deleting File...
del "C:\Users\MyUsername\OneDrive\Dokumenter\Foldername\*.exe"
PING localhost -n 2 >NUL
echo Done!
PING localhost -n 6 >NUL
echo Exiting...
PING localhost -n 4 >NUL
Related Question