6

I am copying a file from one folder into another folder. I would like to name the destination file in this specific way:

filename-currentdatetime-computername-username.txt

How do I do this using a batch file with Windows commands?

I need to get the original filename followed by the current system date time and then the computernaem and the user that is logged on

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

2 Answers2

10

If you don't care about the exact date format, this command will copy a file and include the date, time, user and machine name in the target file name.

copy myFile.txt myFile-%date%_%time%-%computername%-%username%.txt

The date and time will be in the default date format of your OS. Beware that some date formats can contain characters which are not allowed in file names.

To make the command portable you need to specify the format yourself. Here are exampled of how to create format dates that are valid in file names: Format date and time in a Windows batch script

kapex
  • 28,903
  • 6
  • 107
  • 121
  • BEAUTIFUL!! almost works, the thing is this happens: since it puts the date as "Tue 08/16/11......" it does not like the space, how do i get rid of the space or just ignore the space? – Alex Gordon Aug 16 '11 at 17:57
  • I just edited the answer while you made that comment. I think the slashes are the problem. This should help to replace those characters: http://www.intelliadmin.com/index.php/2007/02/create-a-date-and-time-stamp-in-your-batch-files/ – kapex Aug 16 '11 at 18:01
  • Get each part of the date individually and concatenate it to the desired format. If your date is "Tue 08/16/11" use `%date:~5,2%-%date:~8,2%-%date:~11,2%` to get 08-16-11 (untested, I have another format here) – kapex Aug 16 '11 at 18:18
7

%time% is the variable for time
%computername% is the variable for the computer name
%username% is the variable for user name.

You should be able to use those to get all of the data you need to name the file.

MDMarra
  • 214
  • 3
  • 13
  • 2
    Date and Time in their default formats are no good for file names. You can use the tilde "~" modifier to format them. http://www.dostips.com/DtTipsStringManipulation.php – Chris Nava Aug 16 '11 at 18:30
  • 1
    You can run "set" to see all the environment variables that are available to you. – mfinni Aug 16 '11 at 18:37