Search code examples
batch-filefilenamesswap

Batch file to report the filename of the first file in a directory, in a message


I'm setting up a rudimentary directory swap that I plan on using to flip between vanilla and modified versions of Grand Theft Auto V. What I'm shooting for is a batch file that will name-swap the two directories, then tell me via message box which installation variant is in the primary directory. So far, I have a swapper that at least tells me the swap succeeded.

@echo off
ren "Grand Theft Auto V" "Grand Theft Auto V_swap"
ren "Grand Theft Auto V_mod" "Grand Theft Auto V"
ren "Grand Theft Auto V_swap" "Grand Theft Auto V_mod"
msg "%username%" "Files successfully swapped!"

I have added a file in each root dir vanilla.txt and modified.txt, but I don't know how to go any further to use either of their names to the message.

How can I have the message report the name of the text file in the primary directory? Bonus points if you can tell me an easier method.


Solution

  • So you just need run a for loop, assuming that those are the only txt files per directory root:

    @echo off
    ren "Grand Theft Auto V" "Grand Theft Auto V_swap"
    ren "Grand Theft Auto V_mod" "Grand Theft Auto V"
    ren "Grand Theft Auto V_swap" "Grand Theft Auto V_mod"
    for %%i in ("Grand Theft Auto V\*.txt") do msg %username% %%~ni
    

    If however you have other text files in the directory, we can either test their name or instead rename your files to some extension not anywhere else. i.e vanilla.ren and modified.ren then simply do:

    To test the names and only msg when the name match:

    for %%i in ("Grand Theft Auto V\*.txt") do (
        if /i "%%~ni"=="vanilla" msg %username% %%~ni
        if /i "%%~ni"=="modified" msg %username% %%~ni
    )
    

    or dummy extension:

    for %%i in ("Grand Theft Auto V\*.ren") do msg %username% %%~ni