Renaming An Output File According To Date

About a month ago, I had a situation in which I needed to rename an output file to a unique meaningful name. I have a scheduled task that automatically downloads an encrypted file once a day from an FTP server. I wanted to create a batch file that would decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and move the newly renamed, decrypted file into the correct department folder. I thought it would be a pretty simple process to append the date to the filename, since that was the most logical unique identifier in my mind.  Easy-peasy, right?

Holy cow. Google almost failed me. Almost.

Apparently, there are about a bajillion different methods for converting date/time to a text string. Most of the solutions I found were dependent on regional settings, were overly complex (in my opinion) or didn’t give me the format I wanted the date to be in OR didn’t give me a meaningful date at all.

After A LOT of trial and error, I finally stumbled upon this simple solution. (Source)

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

It worked perfectly (i.e., the filename comes out as “2011-06-14.txt”). FTW!

So here’s what my batch file looks like (directory names have been changed, obviously);

cd c:\encryptedfiles\files
echo mypassphrase|gpg --batch --passphrase-fd 0 --output decrypted.txt -d c:\encryptedfiles\files\*.gpg
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
move *.txt M:\decryptedfiles
move *.gpg C:\encryptedfiles\files\archive

For those of you who prefer Windows Powershell, you can also do the same thing via a PS Script;

set-location "C:\encryptedfiles\files"
$date = (Get-Date).ToString('yyyyMMdd')
echo mypassphrase|gpg --batch --passphrase-fd 0 --output "$date.txt" -d "C:\encryptedfiles\files\*.gpg"
Move-Item *.txt M:\decryptedfiles
Move-Item *.gpg C:\encryptedfiles\files\archive

Not so painful!

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
Want to share?
This entry was posted in Techy Stuff and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.