Search code examples
windowsbatch-filexcopy

How can I put a variable into my filename?


I want to copy a .bat file. The copy should be in the same path as the original file and have a random number as a name. This is my approach so far:

@echo
pause
SET nr = %RANDOM%
xcopy "%cd%\*.bat" "%nr%.bat" /q /y
pause

First question: What do I have to do, that the programm creates a .bat file with a number in front of the dot? (because now it creates just a .bat file without anything in front of the dot...)

Second question: How can I stop the question, if the target is a file or a directory?


Solution

  • Besides the fact that the line SET nr = %RANDOM% sets a variable called nrSPACE to a random number preceded by a SPACE, you actually do not need the interim variable nr, you can use RANDOM immediately instead.

    To avoid the file/directory prompt of xcopy, use the copy command instead. Regard that this does not support a /Q switch. Instead you could use > nul to prevent copy from displaying something.

    You do not need to precede the source *.bat with %CD%\, as %CD% just points to the current working directory, but *.bat alone points into that directory anyway.

    Finally, I assume by @echo you actually mean @echo off to suppress command echoes.

    So here is the fixed code:

    @echo off
    pause
    copy /Y "*.bat" "%RANDOM%.bat" > nul
    pause