0

I'm trying to write a short batch file to monitor the data traffic hourly and write it in TXT files. My problem is that I want to give the TXT files the date and time of their creation as their filename.

I already tried to use the %date% and %time% commands, the "date /t" and "time /t" commands or to generate a file beforehand and access it afterwards, but I'm simply not well-versed enough in batch programming to access this file.

netstat -e > C:\Users\User1\Documents\%date%.%time%.txt exit

There should be a file with the name of e.g. "20.02.2016 , 12:06:12.txt" , but I'm either getting a &date file or an error in cmd: "The syntax for filename, directory name, or volume label is incorrect.".

Fabian D.
  • 3
  • 1
  • 3
    A file name may not contain the `:` character (or `/` which other locales would use for dates) Here are some ways to change the format: https://stackoverflow.com/questions/1192476/format-date-and-time-in-a-windows-batch-script – Alex K. May 28 '19 at 16:43
  • If you intend to use the script not only on a single computer, better use a [solution independent of locale settings](https://stackoverflow.com/a/18024049/2152082). As a bonus, this is a sortable format (`YYYYMMDD HHmmss` or `YYYY-MM-DD_HH-mm-ss`) – Stephan May 29 '19 at 08:59

1 Answers1

2
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set filedate=%%c%%a%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set filetime=%%a%%b)
netstat -e > C:\Users\User1\Documents\%filedate=%.%filetime%.txt exit

The first for loop does date /t then is set "/" as a delimiter and reassembles the date without a delimiter.

The second for loop does time /t then using ":" as a delimiter and reassembles the time without a delimiter.

Then we do your netstat command, placing our variables into the filename.

This will not work for all locales, but the general idea is the same. If you live a locale where this solution does not work, then just adapt the code to your own needs. This works for me on my own system, in North America.

shadow2020
  • 1,122
  • 1
  • 3
  • 22