Batch File Adding Date To Filename - batch-file

I wrote a batch file 2 years ago that seemed to work great making a backup copy of an excel spreadsheet daily. All of a sudden 1 day it stopped working properly and began assigning the variables literally instead of pulling the actual date so it just began overwriting itself every day.
I went from getting this file name:
Tasty Schedule 2018 - 04-30-2018
To now getting this filename:
Tasty Schedule 2018 - ~4,2-~6,2-~0,4
Looking at the code it seems obvious where the values are coming from but I am not sure why the date is no longer being pulled. Im assuming there had to be some type of system update that changed something to cause this? What is the best way to fix this? Please see my current code below:
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%MM%-%DD%-%YYYY%
copy "J:\TROY C\2018 Schedule\Tasty Schedule 2018.xlsx" "J:\Joe's Folder\ChocScheduleBackUps\Tasty Schedule 2018 - %stamp%.xlsx"

Launch the following command in a command prompt:
wmic OS Get localdatetime
This should show the date, you can start from there.
Verify your locale settings: the mentioned WMIC command is locale dependent.
In order to make WMIC work, you need to see the following when you run set PATH in a command prompt:
C:\Program Files\7-Zip>set PATH
Path=...;C:\WINDOWS\System32\Wbem;...
(Do no modify C:\Windows directory, your computer will not work anymore)

I solved my issue by adding 'C:\Windows\System32\wbem\' to PATH so that WMIC worked and also adding 'C:\Windows\System32\' to PATH so FIND would work.

Here's an example using RoboCopy instead:
#Echo Off
Set "dStamp="
For /F "Tokens=1-3 Delims=/ " %%A In ('RoboCopy/NJH /L "\|" Null') Do If Not Defined dStamp Set "dStamp=%%B-%%C-%%A"
If Defined dStamp Copy "J:\TROY C\2018 Schedule\Tasty Schedule 2018.xlsx" "J:\Joe's Folder\ChocScheduleBackUps\Tasty Schedule 2018 - %dStamp%.xlsx"

Related

Folder with date format in mmddyyyy needed to be created using a bat file

I want to create a batch file which when clicked will create a folder with the name 12012016.
I tried with the command
mkdir "E:\Meru\Work\Trace Reports\%date:~6,4%%date:~3,2%%date:~0,2%
But its creates with the name 20160112.
Please help
This question implies that you have not tried to understand what is going on with this command...
Split in part: mkdir will create a directory with the name you have given.
The name you have given is build together using a fixxed string, you decided to use E:\Meru\Work\Trace Reports\ and three substrings from the system variable %date%.
Substring in batch works like this: %variable_name:~last character NOT to use,number of characters you need%. In your case it takes the year first, then the month and at last the day. You would just simply change the parts from %date:~6,4%%date:~3,2%%date:~0,2% to %date:~3,2%%date:~0,2%%date:~6,4%.
Notice!
The variable %date% has a different value based on the system settings for the time format. An alternative is the command wmic os get localdatetime which I covered in another answer here that will always have the same output format no matter what the settings are.
If you have read this ==> Windows batch file redirect output to logfile with date/time
You can be able to do like this one :
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
echo stamp: "%stamp%"
pause
echo datestamp: "%datestamp%"
pause
echo timestamp: "%timestamp%"
pause
set MyDateVar=%MM%%DD%%YYYY%
echo My desired Variable Date to use is : %MyDateVar%
pause
mkdir "E:\Meru\Work\Trace Reports\%MyDateVar%"
pause
Because several hours have now elapsed:
mkdir "E:\Meru\Work\Trace Reports\%date:~0,2%%date:~3,2%%date:~6,4%"

Jenkins - sometimes (non-deteministic?) mark builds as failed, because of batch command

I execute following batch ('Execute Windows batch command') through Jenkins. Although it always (tested more than 50 times) works when I build my project 'manually' (when I click on 'build' button), it sometimes crashes during scheduled builds.
REM
REM get date in following format - day name - day - month name - year
REM
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do (set dt=%%a)
set year=%dt:~0,4%
set month=%dt:~4,2%
set day=%dt:~6,2%
if %month%==01 set month=Jan
if %month%==02 set month=Feb
if %month%==03 set month=Mar
if %month%==04 set month=Apr
if %month%==05 set month=May
if %month%==06 set month=Jun
if %month%==07 set month=Jul
if %month%==08 set month=Aug
if %month%==09 set month=Sep
if %month%==10 set month=Oct
if %month%==11 set month=Nov
if %month%==12 set month=Dec
For /f %%# In ('WMIC Path Win32_LocalTime Get DayOfWeek^|Findstr [1-7]') Do (Set DOW=%%#)
if %dow%==1 set dow=Monday
if %dow%==2 set dow=Tuesday
if %dow%==3 set dow=Wednesday
if %dow%==4 set dow=Thursday
if %dow%==5 set dow=Friday
if %dow%==6 set dow=Saturday
if %dow%==7 set dow=Sunday
set dayinfo=%dow% - %day%-%month%-%year%
The error message is as follows:
For> /F
%# In ('WMIC Path Win32_LocalTime Get DayOfWeek|Findstr [1-7]') Do
(Set DOW=%# ) set was unexpected at this time.
if> ==1
set dow=Monday Build step 'Execute Windows batch command' marked build
as failure
Since I am unable to reproduce it - is it possible to make batch command not mark build as failed?
Is it a bug in Jenkins or within my batch file?
is it possible to make batch command not mark build as failed?
Yes, write echo Done or something as the last line in your Execute Windows Batch Command step (not in the batch itself). Since that line will always succeed, the whole step will be marked as successful always. Obviously, you are foregoing any possibility of the script failing for valid reasons though.
Now, the reason your script is failing is because in some circumstances (undetermined), your value for DOW is not set. So the comparison statement becomes invalid as it has no left side.
To avoid this, you should always quote your variables and strings in comparison.
if "%dow%"=="1" set dow=Monday
if "%dow%"=="2" set dow=Tuesday
This way, at least the script won't fail due to syntax errors, however you will still end up with empty dow (and incomplete dayinfo)
To figure out why exactly your dow ends up being empty sometimes, you need to actually see the result of the command that generates it's value. So do the following:
WMIC Path Win32_LocalTime Get DayOfWeek
For /f %%# In ('WMIC Path Win32_LocalTime Get DayOfWeek^|Findstr [1-7]') Do (Set DOW=%%#)
When it's successful, it will display the full output of the command in console. When it fails, you will see the error of that command, and take it from there.

batch file which uses windows OS date

I every month a get a folder named using the year and month (which am not allowed to change). For instance DB201401 (DB = database, 2014 = the year and 01 =the month). I was wondering if there was a way to make a batch file, which finds the correct folder of the same year and month based on windows OS Date?
or maybe just find the folder by the month, ignoring the "DB2014"?
#echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "curdt=%%a"
set "Year=%curdt:~0,4%"
set "Month=%curdt:~4,2%"
echo DB%YEAR%%MONTH%
Change the echo to whatever you want to do with the foldername.
This depends on WMI - so it won't work on very very old Windows versions without WMI.
Wouldn't that just be the latest "DB2*" directory date?
for /f "delims=" %%a in ('dir /b /ad DB2*') do set currdir=%%a&goto done
:done
echo %currdir%
but that assumes that the only DB2* directories are of format DBccyymm

Windows command prompt hangs for indefinite time

I have a script that performs upgrade to a database.
The script also logs before the upgrade starts, but when this script tries to access the log file it hangs for an indefinte time.
The line that's causing the issue is:
%LOGMESSAGE% Start update %UPDVERSION% .
LOGMESSAGE is a cmd file which is as follow:
SETLOCAL enabledelayedexpansion
SET /A FT=500
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year
/Format:table') DO (
IF NOT !FT!==500 GOTO proceed
SET FD=%%F-%%D-%%A
SET FT=%%B:%%C:%%E
:proceed
SET /A FX="DS"
)
endlocal
The main function of the LOGMESSAGE is to get the current system time.
The log file into which the scripts writes to has no issues and so does the function LOGMESSAGE, as the log file is written many times before the line %LOGMESSAGE% Start update %UPDVERSION% . is called. The script seems to work without any hassle on many other computer, but I am having an issue with one server, the server is running windows server 2003 R2 SP2.
Any idea what the issue might be?
try this:
#ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
SET /A FT=500
FOR /F "tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table^|find "20"') DO (
IF NOT !FT!==500 GOTO proceed
SET FD=%%F-%%D-%%A
SET FT=%%B:%%C:%%E
:proceed
SET /A FX="DS"
)
endlocal
If you just want to get the date and time, you can use
DATE /T
TIME /T
instead of WMI.
Three comments:
.cmd files are rare - normally, .bat files are used. There are minor differences between the two, but I'm not sure whether they would be relevant (I can no longer remember them...)
It's perfectly legitimate to have have a line-break just before the opening single-quote and just after the closing. A break in the middle of the command, I'm not sure about - not saying this IS a problem, but it's so easily eliminated.
I'm no longer sure, since I rarely use XP any more, and never S2003 - but ISTR there were problems with having a label within a block statement. The label seemed to end the block.
So - I'd suggest
running the routine as a .bat instead of a .cmd, using
for...(
'whatever whatever...'
) do (
structure, and implementing whatever tomfoolery is happening about FD, FT and FX within a subroutine.

Create bat or script file to delete files

I would like to know how to create a bat file which on its first run would store the system date and on subsequent run delete a particular file 30 days later.I think if a bat file can be created that would store system date on its first run and the second bat files reads the first file for the date would be better.But how?
As #devio commented, PowerShell is definitely more fully featured: PowerShell Quick Reference
If it has to be a Batch file, this reference explains most commands.
I love powershell, and it is certainly more powerful than batch files, but for this it shouldnt really matter what you use, so if you're comfortable with your batch files you should be able to stick with them.
The only way you'll be able to later recover that date is to store it somewhere (or have your task running the whole time which is unrealistic - think reboots among other things)
You could write the deletion date to the registry or a text file or somewhere else that is 'known', but then you need to have something else running to check 'if its time to act'.
I'd be inclined to just create a scheduled task for the delete during the original script so that I wouldn't have to check up on it. You could even have the delete script you've scheduled clean up the task when it's done.
You could use something like a windowscripting host vb script or js script file. Also scripting languages such as php, python or perl would allow you to do something like this easily and possibly give you much greater flexibility than a shell script.
It's going to take a while to answer this one, but here's the first thing to suggest.
When you want to have a single .BAT (or .CMD) which does something and also does something later based on the first something, one can use the "flag parameter" technique. For example, in a script which accepts a wildcarded list of files to manipulate one could do as follows:
::foo.cmd
#echo off
if %1#==# goto fail
set f=%1
if %1==! goto inner
for %%x in (%f%) do cmd /c %0 ! %%x
goto done
:inner
set f=%2
echo do something with %f%
goto done
:fail
echo %0 {wildcard}
:done
The script is actually written such that it can be called anything, and it will call itself (using %0).
Now how to do date arithmetic is going to take some time to figure out. I hope that much at least gets you started in the right direction.
my setup after after completion of installation would run a bat file(once) that should get the system date(install date) and store in a text file.the main program would be called by another batch file that would read the text file every time for the date assisting it to delete particular files after "N" number of days referencing the install date in the text file.
HI MARK BRACKETT,
when I run batch1 the date is MM\DD\YYYY.But when I run batch2 the startdate is DD and the startmonth is also DD.The final equation is if rundate==nowdate execute command,it should be rundate=>nowdate,cause if pc not switched on rundate.secondly months with 31days the rundate would 31st next month
VBScript, PowerShell, or C# (I use CS-Script to run my C# scripts) would be much cleaner - but sometimes I enjoy a little batch file challenge.
So - this is for 1 month from the current date and time, but it gives you the idea. To actually figure 30 days, I suspect you'd need about 50 lines of IF statements. Or, a single external EXE to calculate it for you.
I think there's a cleaner way to use SET itself to split out the date parts, which would cut this down by about 3 lines - but I don't recall the syntax ATM.
Batch1
ECHO %DATE% > start.txt
Batch2
: Get start date
FOR /F "tokens=1* delims= " %%i IN (start.txt) DO set startDate=%%j
FOR /F "tokens=1,2 eol=/ delims=/ " %%i IN ('echo %startDate%') DO set startMonth=%%i
FOR /F "tokens=1,2 delims=/ eol=/" %%i IN ('echo %startDate%') DO set startDay=%%j
FOR /F "tokens=2,3 delims=/ " %%i IN ('echo %startDate%') DO set startYear=%%j
: Get run month and day as YYYY-MM-DD
SET /A runMonth=%startMonth% + 1
IF %runMonth% LEQ 10 SET runMonth=0%runMonth%
SET runDay=%startDay%
SET runYear=%startYear%
SET runDate=%runYear%-%runMonth%-%runDay%
: Get current month and day as YYYY-MM-DD
FOR /F "tokens=1* delims= " %%i IN ('echo %DATE%') DO set nowDate=%%j
FOR /F "tokens=1,2 eol=/ delims=/ " %%i IN ('echo %nowDate%') DO set nowMonth=%%i
FOR /F "tokens=1,2 delims=/ eol=/" %%i IN ('echo %nowDate%') DO set nowDay=%%j
FOR /F "tokens=2,3 delims=/ " %%i IN ('echo %nowDate%') DO set nowYear=%%j
SET nowDate=%nowYear%-%nowMonth%-%nowDay%
: Compare
IF %nowDate% GEQ %runDate% ECHO Delete!
Note that this doesn't handle year changes appropriately (it'll delete on the year change).

Resources