Dynamic date in batch file - powershell

i am running the following command in a cmd:
Prog.exe -time Components_2016_04_19_11.ss
I want to write a batch file that will be run hourly and i need the date in the command to change accordingly - the date needs to be in the format above, and the last part of the date is the current hour minus 7 hours
So if the time now is 1/1/2016 20:43 the command will look like this
Prog.exe -time Components_2016_01_01_13.ss
i need help creating the appropriate batch file
Thanks

For future reference, questions resembling "Write this for me. Here are my requirements." aren't well-received around here. But this time, just to prevent any more unhelpful answers from being posted, I'll help you out with a solution.
Pure batch is really cumbersome with date math. Compensating for midnight, month changes, leap years, etc. can be a nightmare. It's much easier to use a different language -- one which has a proper Date object that will handle calendar quirks without having to hack around them.
Here's a PowerShell solution to your problem:
Prog.exe -time ("Components_{0}.ss" -f (Get-Date).addHours(-7).toString("yyyy_MM_dd_HH"))
That's it, just a one-liner. If you require a batch script, you can employ the PowerShell helper to perform the date math heavy lifting.
#echo off & setlocal
for /f "delims=" %%I in (
'powershell -noprofile "(Get-Date).addHours(-7).toString('yyyy_MM_dd_HH')"'
) do (
Prog.exe -time Components_%%I.ss
)
goto :EOF

Get-Date
Get-Date | Get-Member

you can use this:
$GBL = 0
do{
Prog.exe
Get-Date
sleep 3600
}
while($GBL -lt 1)
$GBL it's a infinity variable for the loop. inside of the do execute the program and use the sleep for wait 3600 seconds or 1 hour for execute again. Get-Date it's for mark the date and time when the code it's executed.
I don't understand if you need this or something else.
You can modify the line of Prog.exe with the code you need.
If you answer me i can help you.
Have a good day (:

Related

Is it possible to specifically compare two dates in batch?

I was wondering if it's possible to compare a specific date (in the MM/DD/YY format) to the current system date, and get the difference in minutes?
In my past questions, I've been able to grab the dates of processes and folders and create the conversion to minutes, but I'm stumped.
My project uses Batch/CMD and Powershell, so any of those formats would be more than acceptable.
Here's the code that I use for grabbing dates to minutes with processes:
if exist "C:\Windows\Prefetch\JAVAW*.*" (
for /f "usebackq" %%A in (`
powershell -NoP -C "[int]([datetime]::Now - (gci 'C:\Windows\Prefetch\JAVAW*.*' -Force).LastWriteTime).TotalMinutes"
`) do set "AgeMinutes=%%A"
)
if exist "C:\Windows\Prefetch\JAVAW*.*" echo JAVAW.pf was modified %AgeMinutes% minutes ago.
if not exist "C:\Windows\Prefetch\JAVAW*.*" echo Error: file not found.
Is a comparison to the current date (and outputting it into minutes) possible?

Add Date and Time stamp to powershell exported file

I am new to scripting but at my work place I see that they are storing warnings, errors and notes from logs of different programs under one file using the below command in a batch file:
check_log.bat > tlglogs
PS: If it matters the different logs and the output tlglogs are in the same Windows folder.
I would like to add a date time stamp to the tlglogs each time I run the batch file. Could you please let me know how to proceed as I am not familiar with scripting? I tried the below via Dr. Google's help but it did not help:
check_log.bat >tlglogs_%Date%
Thanks for your time and help. It is highly appreciated!
Cheers!
In Powershell you can get the current date like below:
Get-Date
You can save it to a variable and also define the format of the returned date.
$d = Get-Date -Format "ddMMyyyy"
So this will return a date in the format like 04082016 and save it in the variable $d which we can use for export.
check_log.bat > "tlglogs_$d"
That should do what you want.
Thanks Junaid, adding the below code in the batch file worked for me:
#echo off
set startDate=%date%
set startTime=%time%
set sdy=%startDate:~10%
set /a sdm=1%startDate:~4,2% - 100
set /a sdd=1%startDate:~7,2% - 100
set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100
check_log.bat *.log > tlglogs%sdy%.%sdm%.%sdd%-%sth%.%stm%
If there is a much easier way please do let me know. Thanks again!

How to get Current Date - 1, -2 ,-3 , -4 in Batch

This is what i would like to do:
Get Current Date, which is easy --- %DATE%
DO Current Date - 1, which i cant seem to get as i have tried different options.
I would like to get last 4 dates from the current date and then store them in 4 different variables. Then Convert each of these date into YYYYMMDD format.
So %DATE% gives me 06/04/2016.....
%DATE%
-1 should give me 05/04/2016 stored in Variable say Date1........
-2 should give me 04/04/2016 stored in Variable say Date2........
-3 should give me 03/04/2016 stored in Variable say Date3........
-4 should give me 02/04/2016 stored in Variable say Date4........
then i would like to convert value stored in each of these variables into YYYYMMDD
For ex:
05/04/2016 to 20160405 ....
04/04/2016 to 20160404 ....
03/04/2016 to 20160403 ....
02/04/2016 to 20160402 ....
with a little help from powershell:
#echo off
for /l %%d in (0,1,4) do (
for /f "tokens=*" %%i in ('powershell get-date -date $(get-date^).adddays(-%%d^) -format yyyyMMdd') do set _Date%%d=%%i
)
set _date
Explanation (copied word by word from TessellatingHeckler's comment - couldn't formulate it better):
for /L is a batch file loop which counts numbers, 1 2 3 4, and each
time through it calls PowerShell script engine with a for /f command
which is a bit of a batch file workaround. The PowerShell command gets
the current date, adds -X days to it, then gets the resulting date,
and formats it in the way you want and returns it to the batch file,
which gets one line of text back, and uses that in the do section to
set the environment variable. tokens=* tells the loop not to split the
line of text up, and the ^ are to escape special characters in batch
files
for /l works like this: for /l %%i in (<start>, <step>, <end>). In other languages it would read something like FOR i=<start> TO <end> STEP <step>
The powershell command assembles like this:
get-date - get today's date.
get-date -date <some date> get the date of <some date> (seems absurd, but in fact means "take the string <some date> and convert it to a valid date").
Now replace <some date> with $(get-date).adddays(x) - which means "take today, and add x days"
last step is formatting the resulting date to the desired format with -format <formatstring>
you can read powershell's help from cmd with powershell get-help get-date or more detailed: powershell Get-Help Get-Date -Online

How do I find last Sunday's date and save it in a variable in a Windows batch file

I have a script that needs to connect to an ftp server and download a file that is only created on Sunday and Sunday's yyyy-mm-dd-hh-mm-ss is appended to the file name. I need to find the last Sunday's date (based on today's date, I assume) and convert it to yyyy-mm-dd (I don't care about the time) so I can construct the filename in my ftp script. I have searched a lot of threads on this and other sites, but I'm kind of a novice at batch syntax. I cannot make assumptions about the date format on the machine that will run this script, but it will be in the same timezone as the ftp server and it will be running at least Windows 7. I thought about using the PowerShell solution in HOW to find last SUNDAY DATE through batch but I've read there are issues with PS script portability. Any help is greatly appreciated. Let me know if I need to provide more detail. Thanks!
(Get-Date).AddDays(-(get-date).dayofWeek.value__)
A couple years ago I wrote a batch script to find yesterday's date. I made it able to calculate 'yesterday' based on today's date. It takes into account months ending on the 30th or 31st, and even the next few leap years. The way I wrote it expects the date to be in the format 'Wed 02/24/2016' or 'ddd MM/DD/YYYY', so it may not be useful to you.
As I look at it now, it's probably more complicated than it needs to be and could probably use some cleanup, but it worked for my purposes. You might be able to modify it somehow to make it find last Sunday, instead of yesterday.
set yearCounter=0
set yyyy=%date:~10,4%
set mm=%date:~4,2%
set dd=%date:~7,2%
::use these to override the actual date values for testing
::set yyyy=xxxx
::set mm=xx
::set dd=xx
if %dd%==01 goto LDoM ::Last Day of Month
set DS=%yyyy%%mm%%dd%
set /A yesterday=%DS%-1
goto endyesterday
:LDoM
set /A lastyyyy=%yyyy%-%yearCounter%
if %yesterday:~4,2%==01 set lastmm=12& set lastdd=31& goto LDoY ::Last Day of Year
if %yesterday:~4,2%==02 set lastmm=01& set lastdd=31
if %yesterday:~4,2%==03 set lastmm=02& goto february
if %yesterday:~4,2%==04 set lastmm=03& set lastdd=31
if %yesterday:~4,2%==05 set lastmm=04& set lastdd=30
if %yesterday:~4,2%==06 set lastmm=05& set lastdd=31
if %yesterday:~4,2%==07 set lastmm=06& set lastdd=30
if %yesterday:~4,2%==08 set lastmm=07& set lastdd=31
if %yesterday:~4,2%==09 set lastmm=08& set lastdd=31
if %yesterday:~4,2%==10 set lastmm=09& set lastdd=30
if %yesterday:~4,2%==11 set lastmm=10& set lastdd=31
if %yesterday:~4,2%==12 set lastmm=11& set lastdd=30
set yesterday=%lastyyyy%%lastmm%%lastdd%
goto endYesterday
:february
set leapyear=n
set lastdd=28
if %yesterday:~0,4%==2016 set leapyear=y
if %yesterday:~0,4%==2020 set leapyear=y
if %yesterday:~0,4%==2024 set leapyear=y
if %yesterday:~0,4%==2028 set leapyear=y
if %leapyear%==y set lastdd=29
set yesterday=%lastyyyy%%lastmm%%lastdd%
goto endYesterday
:LDoY
set /A yearCounter=%yearCounter%+1
set /A lastyyyy=%yyyy%-%yearCounter%
set yesterday=%lastyyyy%%lastmm%%lastdd%
:endYesterday
#echo off
echo %yyyy% %lastyyyy%
echo %mm% %lastmm%
echo %dd% %lastdd%
echo.
echo today = %yyyy%%mm%%dd%
echo yesterday = %yesterday%
Working with date and time using pure batch can be done, but it is not very convenient.
The GetTimestamp.bat utility makes date/time computations and formatting simple within a batch context. It is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward. The previous link points to the most recent version. The utility was first introduced with a number of examples at http://www.dostips.com/forum/viewtopic.php?t=4847.
Full documentation is available from the command line via getTimestamp /?, or getTimestamp /?? for paged output.
With GetTimestamp, the solution can be as simple as:
#echo off
:: Get the current day of the week, with 0=Sunday, 6=Saturday
:: to be used as an offset from today to get the most recent Sunday
call getTimeStamp -f {w} -r offset
:: Use the offset to get the most recent Sunday in YYYY-MM-DD format
call getTimeStamp -od -%offset% -f {iso-dt} -r lastSunday
:: Show the result
echo lastSunday=%lastSunday%
Try the following from a batch file:
for /f "usebackq" %%d in (`powershell -noprofile -command "'{0:yyyy-MM-dd}' -f [DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek)"`) do set "lastSunday=%%d"
echo %lastSunday%
:: -> e.g., "2016-02-21", when run on 2016-02-25
To try this directly on the command prompt, replace %%d with %d.
The PowerShell expression at the heart of the command,
[DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek),
which calculates the date of the most recent Sunday, was gratefully borrowed from the answer that you link to in your question.
'{0:yyyy-MM-dd}' -f ... applies the desired yyyy-mm-dd formatting to the date.
powershell -noprofile command ... invokes the PowerShell expression and outputs its result to stdout.
for /f "usebackq" %%d in (`...`) do set lastSunday=%%d captures the output from the PowerShell command and assigns it to batch variable lastSunday.
While invoking PowerShell for just one command from a batch file will be slow, being able to calculate the desired date so conveniently probably outweighs performance concerns.

HOW to find last SUNDAY DATE through batch

How to find 'last SUNDAY DATE' through batch command?
what I was trying is
echo %date:~4,2%%date:~7,2%%date:~10,4%
this is good for current date
but for last Sunday date... can anyone suggest any logic through batch.
Windows PowerShell:
[DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek.value__)
Sorry the environment variable %date% in Batch (.bat) files sounds uneasy to do calculations.