How to automate the file name in bat file


The following code opens a db file (sqlite language) and exports the resulting query to a file on my desktop. Up here all good. What I want is for the file name to be different every time the batch is executed.

sqlite3 -cmd ".headers on" -cmd ".separator '|'" -cmd ".once holaa.xlsx" -cmd "SELECT * FROM analysis;"  C:\ProgramData\PROISER\ISASPSUS\datastore\dsfile.db <nul

A further thing is happening to me that executing it by double clicking works well for me but doing it from a scheduled task does not create the file.

asked by Santiago Corso 30.08.2018 в 17:43

1 answer


You're actually asking two questions in one.

1. How to make the file name different, every time it is executed.

You do not give more specifications, so I will use the old technique of having the name of the file contain the date and time, in this way, every time you execute it, it will have a different name.

To achieve this, I will use an environment variable, to which I assign the value of the current date and time, and finally I use it as a parameter to create the file:

set fch=%date:~11,4%%date:~8,2%%date:~5,2%%time:~0,2%%time:~3,2%%time:~6,2%
sqlite3 -cmd ".headers on" -cmd ".separator '|'" -cmd ".once holaa%fch%.xlsx" -cmd "SELECT * FROM analysis;"  C:\ProgramData\PROISER\ISASPSUS\datastore\dsfile.db <nul

The positions I use to construct the value of the variable fch depend on the regional configuration, it is likely that your team must make some adjustment to make it work.

To test on your computer, you can create and run this bat:

@echo off
set fch=%date:~11,4%%date:~8,2%%date:~5,2%%time:~0,2%%time:~3,2%%time:~6,2%
echo %fch%

On my computer, it produces the following result:

2. From a scheduled task it does not create the file.

Here may be one or two of the problems that I describe below.

  • The scheduled task is executed under a user account, which can be the one of the system, the one you indicate at the time of creating the task (user and password) or the account with which you logged in to Windows. This user account must have read and execute permissions to the folder where the .bat file is located (and the programs it invokes) and write permissions to the folder where the output file is deposited. If the account does not have sufficient permissions, you will not find the result.

  • Your script includes a relative path to the output file. It is common to believe that this route will always be the folder where the .bat is, but the current route of the process may be another. If you do not indicate the current route at the moment of creating the action of the scheduled task, it will be the default route of the programmer (who now can not say what it is). You can solve this, either by indicating an absolute path so that the file is always created in the same folder, or by setting the current path of the process when creating the action, as shown in the image (in Windows 10) :

answered by 30.08.2018 / 21:35