Batch Script For File Date/Time - date

I know there are similar questions but I have not been able to make any work. I need to check a particular file date and time against the current date and time.
So far I have
Set cdate=%date%
Set filename="c:\myfile"
If Not Exist %filename% GOTO CREATEFILE
For %%f In(%filename%) DoSet filedatetime=%%~tf
If %filedatetime:~0,-9%" == "%cdate% GOTO SHOFILE
My problem is that the cdate returned has the day of the week included in the date but the file date does not. Example cdate= Thur 1/01/2015. How can I get the cdate not to have the day of the week?
Thanks

For %%f In (%filename%) Do Set "filedatetime=%%~tf"
If "%filedatetime:~0,-9%"=="%cdate:~4%" GOTO SHOFILE
Note the required space after in and do
The set "var=value" syntax ensures that any trailing spaces on the batch line are not included in the value assigned to var.
if /i "%var%"=="value" performs a comparison on variables/values containing separators (eg spaces) The '/i' make the comparison case-insensitive if required.

Your cdate can be set like this:
SET cdate=%date:~4%
This has the following output:
echo %cdate%
01/01/2015

Related

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.

Find multiple values in different lines using command-line | CMD

I have multiple results (Radiology, Labs, Pathology, Transcriptions) for the same patient in a file and I am only interested in getting results for a set of particular values. For example: I want to look for a radiology report on the first line and patient MRN 123456789 on the second line.
Can this be achieved using findstr? Thanks
MSH|^~\&|RADIOLOGY|1|SCM||20150303||ORU|20150303|T|2.3|20150303
PID||1111111|123456789^^^MRN_SB^||TEST^PATIENT^^^||19000101||^^||
PV1|1|E|ER^ER^1^SB||||||||||||||||||||||||||||||||||||||||||||||
ORC|RE|36543654|36543654|3003487889
#ECHO OFF
SETLOCAL
:: remove variables starting $
FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
SET "found="
SET "mrn=%1"
FOR /f "delims=" %%o IN (q29931949.txt) DO (
FOR /f "tokens=1-4delims=|" %%a IN ("%%o") DO (
IF DEFINED found IF "%%a"=="PID" (
SET "$2=%%o"
CALL :report "%%b" "%%c" "%%d"
)
SET "found="
IF "%%a"=="MSH" IF "%%b"=="RADIOLOGY" SET found=Y
IF "%%a"=="MSH" IF "%%c"=="RADIOLOGY" SET found=Y
IF DEFINED found SET "$1=%%o"
)
)
GOTO :EOF
:report
SET "field=%~1"
IF NOT DEFINED field GOTO :EOF
FOR /f "tokens=1delims=^^" %%r IN ("%~1") DO SET "field=%%r"
IF "%field%"=="%mrn%" FOR /F "tokens=1*delims==" %%r In ('set $') DO ECHO(%%s
shift
GOTO report
I used a file named q29931949.txt containing your data for my testing.
You don't really supply enough information to produce a result. For instance, is "MRN" a required data item?
This procedure will find two consecutive lines, the first one having "MSH" in he first column and "RADIOLOGY" in the second or third and the second line having "PID" in the first column snd either the second, third or fourth column containing the target number.
You'd run the routine using thisbatchaname 123456789
It accepts the parameter 123456789 and assigns that to mrn.
It then reads the file and assigns each line in tun to %%o, and tokenises the line on |, applying tokens 1-4 to %%a..%%d rspectively.
The main loop sets found to empty and then to Y only if the first field is MSH and the second or thid RADIOLOGY. If the found flag is set, the original line in %%o is applied to $1. Only if found is set at the start of the loop (which means that the previous line is MSH/RADIOLOGY) will the routine :report be called after $2 has the original contents of the second line assigned.
The :report routine sets field to the first parameter to see whether there are remaining parameters to process. The for then assigns the part of the field up to the first caret (^) to field. If this matches the mrn input from the command line, then the $ variables are echoed to the console (you don't say what you actually want to do with the data). Regardless, the remaining parameters are checked.
The reson for checking the second/third(/fourth) parameter is to cater for the presence or absence of data in the fields as consecutive | characters are interpreted as a single delimiter.
Find a HL7 parser library for Your programming/scripting language of choice and use it. It is not worth it to write a HL7 parser from scratch. There should be libraries available for all popular languages that You can use.
If You then have specific questions, feel free to ask again.

batch rename files keeping substring and adding mm and yy

I have a series of files that have long filenames. For each filename that contains a hyphen I would like to keep the substring in position 6-8, append the _FM07_FY14.prn to the name and ignore the rest of the original filename. The new extension is now .prn. The two digits 07 stands for the month and 14 is the year. The month and year can be found from the "date created" property. Will appreciate it if you can show me how to automatically capture this mm and yy from the date created. Hardcoding this part is okay too since I can sort files by created dates and put them in separate folders.
For example
aaaaaD07.dfdd-1234.A.b.1233 new filename will be D07_FM01_FY14.prn
bbcbaA30dls-d343.a.123d new filename will be A30_FM01_FY14.prn
cdq0dG12ir3-438d.dfd.txt new filename will be G12_FM01_FY14.prn
This is the .bat file I come up with after reading many posts on here, and I don't know how to extract the mm and yy so I hard code it. I am not familiar with Powershell. I can only handle a .bat or .cmd file and run it at the command prompt. Any and all help will be highly appreciated. Thanks!
#ECHO OFF
SETLOCAL
for %%F in (*.*) do (
SET "name=%%a"
set "var=_FM01_FY14.prn"
ren *-* "%name:~6,8%var%"
)
*endlocal*
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\one"
PUSHD %sourcedir%
FOR /f "delims=" %%a IN (
'dir /b /a-d "*" '
) DO (
SET name=%%a
SET fdate=%%~ta
ECHO(REN "%%a" "!name:~5,3!_FM!fdate:~3,2!_FY!fdate:~8,2!.prn"
)
popd
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
The format that I use for date is dd/mm/yyyy If yours is different, then you'll need to change the offset in the !fdate:~m,2! phrases. The value of m is the offset into the date string from the first character (the second parameter is the number of characters to select.)
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Batch File If modified date = yesterday date (run command)

Ok, I'm using Rob Van der Woude yesterday.bat code along with some code that I've put together with the help of others posts here.
I have a file that I first want to see if it exists with yesterday's date, if true, then I'll do some other stuff. The problem I am stuck on is comparing the filedate to "yesterday's" date. When I echo them to screen, they both look exactly the same, but my batch file says they are not. The first part of code is from yesterday.bat to show where I am inserting my code. Any guidance is greatly appreciated.
Display the results
ECHO Format: YYYYMMDD (%LocalFormat%)
ECHO.==================================
CALL ECHO Yesterday: %SortYest% %yLocal%
ECHO Today: %SortDate% %Today%
:: Check if file gams1bu from yesterday exists
SET filename="B:\data\backup\gams1bu"
IF NOT EXIST %filename% GOTO log
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
::This displays the results of the two variables
CALL ECHO %yLocal%
CALL ECHO %filedatetime:~0,-10%
IF %filedatetime:~0,-10% == %yLocal% goto same
goto notsame
:same
echo Dates the same, do some code here
goto next
:notsame
echo Dates NOT the same, do some code here
Even though the dates appear identical when I run this, the batch file goes to :notsame ????
The
SET filename="B:\data\backup\gams1bu"
IF NOT EXIST %filename% GOTO log
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
doesn't seem to be setting filedatetime on my prompt (cmd.exe)
This will give you the current date in the format YYYYMMDD 20121128:
for /F "tokens=2-4 delims=/ " %i in ('date /t') do SET datestamp=%k%i%j
SET datestamp=20121128
C:\>echo %datestamp%
20121128
(The original command is from:)
http://www.sprint.net.au/~terbut/usefulbox/msdoscmds.htm
Hi
If you need to get the date of a file in YYYYMMDD format, you can do this:
Assume the name of the file is FILE_YOU_NEED.txt
for %a in (FILE_YOU_NEED.txt) do set FileDate=%~ta
for /F "tokens=1-3 delims=/ " %i in ('echo %FileDate%') do SET datestamp=%k%i%j
If your filedatetime variable has both the date and time you can try
comparing on a variable that only has the date, but not the time:
set FILEDATETIME=12/02/2012 13:45
echo %FILEDATETIME%
12/02/2012 13:45
set FILEDATEONLY=%FILEDATETIME:~0,10%
echo %FILEDATEONLY%
12/02/2012

Need assistance padding numerical month and day with leading 0

I am working within a batch file and need to pad a single digit with a leading 0 if under 10. I have the values in environmental variables. They are month and day, I need to pad to match file structure I am working against. I am using vbscript to return a date that comes back in the following format "7/16/2009". Need it to look like "07/16/2009" and most inportantly need each item in separate EVs.
VBscript:
WScript.Echo DateAdd("d", Date, -36)
Batch:
for /F "tokens=1-3 delims=/" %%x in ('cscript //nologo get36thday.vbs') do (
SET YYYY=%%z
SET MM=%%x
SET DD=%%y)
VBScript:
dteOldDate = Now()
strNewDate = Right("00" & Month(dteOldDate), 2) & "/" & Right("00" & Day(dteOldDate), 2) & "/" & Year(dteOldDate)
For the batch script, I don't know the exact syntax but a batch script can return a specified number of characters from the right side of a string.
So, append the month after a "0" character and take the 2 right-most digits. It would probably look something similar to this:
SET MM=0%%x
SET MM=%MM:~-2%
1 become 01
5 becomes 05
10 stays 10
Here is my method of padding strings.
In this example, MYVAR will be padded to five zeroes.
SET MYVAR=00000%MYVAR%
SET MYVAR=%MYVAR:~-5%
Athough the other answers are useful if you don't know the length of the string you want to pad with zeros up front, for dates and times a simple string replacement will do.
set hour=!TIME:~0,2!
set hour=!hour: =0!
In short, if there is a space it will be replaced by a 0.