Get/Set Unknown Filename Variable with Batch

I am working on a document import utility that imports a text document from a specific location. The filename of the document is unknown and I need to find out how to determine the name of the file and make it a temporary value in my script so that it knows what the file name is so that it can ultimately open it in notepad automatically. I tried using *.txt to see if notepad would just open the first file matching this filter within the working directory but it doesn't work. How do I get and then set this unknown filename variable once the document has been copied to the working directory? Here is the code I have for the function so far:

@ECHO OFF

:CHECK
IF EXIST "*.txt" GOTO :AUTOEDIT
IF NOT EXIST "*.txt" GOTO :RUN

:AUTOEDIT
%SYSTEMROOT%\Notepad.exe "*.txt"
GOTO :END

:RUN
%SYSTEMROOT%\Notepad.exe
GOTO :END

END
2

1 Answer

Create this batch file and save it in the folder where the misterious txt file is beeing copied to.

@echo off

:CHECK
for %%a in (*.txt) do (
set TxtFile=%%a
Goto :AUTOEDIT %TxtFile%
)

echo Checking for txt files every 10 seconds...
timeout /t 10 > Nul
cls
Goto :CHECK

:AUTOEDIT 
cls
echo.
echo Hello, I found a file called "%TxtFile%", Press any key to open it...
pause > Nul
%systemroot%\notepad.exe %Txtfile%
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest