Search code examples
batch-filecmd

How to make the user input the file's name and extension?


I'm trying to improve a program I made and I want the working-file (the file the user wants to work on/want information about/ etc.) to be variable/not determined right from the start by the code/the program as well as the working-directory.

I managed to get the working-directory to be variable (code below), but only where the bat file is (so for this to work the user would have to copy the bat file and place it in the folder it wanted it to work). I wanted it to be possible for the user to write the directory address.

I managed to get the directory to be variable (by user's input) (code below).

set /p "source_folder=Write folders directory: "
echo %source_folder%

Now, for the file, I don't really know how to properly do it. The code below gives errors (obviously), but could it perhaps still partially used and there is only missing some code to make it work?

set filename=%%~nxi
set extension=%%~x1

nxi /d%filename%
x1 /d%extension%

echo The working-file is
echo %filename%%extension%

Or perhaps there is something much simpler, a very simple command that even a beginner should already know that I do not know? (all this is just a small part of the program, in another question I made, I have the full program Program to find duplicated files and eliminate them in a certain folder plus its sub-folders )


Solution

  • To allow the user to enter input for a directory name, add such a line:

    set /p "Source_folder=Enter the directory path: "

    Then, do this again for the filename:

    set /p "File_name=Enter a file name to search (without extension): "

    And another line for the type:

    set /p "File_type=Enter a file type to search (for example: docx): "

    Then you will perform the search in this way:

    for %%a in ("%source_folder%\%File_name%.*") do @echo %%~Ta %%a
    for %%a in ("%source_folder%\*.%File_type%") do @echo %%~Ta %%a
    

    The computer will search the source folder for the name of the entered file (of any type), as well as any file of the entered type.