bat file substring

Automatic Windows Process Dump Script

I have a laborious task at the moment, of exporting our server process list to see how much memory certain programs are using. I was getting a little bored of remote accessing the server through VNC so decided to use a BAT file to do the work for me. However the problem was, I wanted to save each dump as the date it was run and this wasn’t easy in a BAT file.

C:> TASKLIST.EXE /V /FO CSV > 2011-06-14.txt

That is the function I have been using. So this is what I want the script to do.

To get the actual current date, I used this call:

ver | date > date.txt

This creates a file called date.txt and inserts the current date (with another line which I can ignore)

So, now I want to read this file into memory so I can get the date from it.

set /p var= <date.txt

This reads in the first line of the file and stores it in the var variable

The line is:

The current date is: 14/06/2011

So lets get rid of the preliminary string as we don’t want it

set var=%var:~21,10%

This sets the variable “var” to be a substring of itself, starting at character 21 and fo 10 characters. Get it?

All we need to do now is chop and change the date so I get it in the format I want, from dd/mm/yyyy to yyyy-mm-dd (I am a database sucker, so always use these format dates)

A little more confusing looking, but does the same as the previous line, picking bits of the string and putting them into the var variable.

set var=%var:~6,4%-%var:~3,2%-%var:~0,2%.txt

If you read it, you will see it takes the 4 characters starting from position 6 (this is the year), adds a “-” symbol, then 2 characters starting from the 3rd, another – and then the first 2 characters

Put it all into a batch file, and it looks like this:

@echo off
REM Chris Tate-Davies
REM Export the current process list and save as todays date.txt
REM To be run from the schheduled tasks every day

REM delete any existence of previous date
del date.txt

REM Get the date and put it in a file
ver | date > date.txt

REM open the new file and put the date in variable "var"
set /p var= <date.txt

REM chop out the string so we just have the date
set var=%var:~21,10%

REM re-allign the date parts to yyyy-mm-dd
set var=%var:~6,4%-%var:~3,2%-%var:~0,2%.txt

REM run the tasklist and pass the %var% to output to
tasklist.exe /V /FO CSV > %var%

Now all I need to do is add it to the scheduled tasks and then I can pick up the files once a week instead or stopping what I am doing every day to do it.