Dos command and its output - batch-file

All,
Please guide me, how to print the o/p of below command in dos window? Being new to dos command, I do not know what below string mean?
set ts = %date:~4,2%%date:~7,2%-%time:~0,2%%time:~3,2%
Thanks in advance

Welcome to the cmd prompt.
echo is the command that will display a value to the screen (ex: echo %date%)
set ts is setting a variable (ts) which can later be called like this: %ts%
%date% is a variable that will return the system date. %date:~4,2% will give the month (numeric) and %date:~7,2% gives the day of the month (numeric).
%time% is also a variable, but this on returns the time (24 hour). %time:~0,2% gives the hours (24 hour style so 1pm=13). %time:~3,2% gives the minutes.

That is setting an environment variable named ts. To display the value, add this line after it:
echo %ts%

This is setting a variable using some substring operations.
This %date:~4,2% means:
get the date from the machine;
remove the first 4 characters of it;
from the result, get the first 2 characters;
The rest is repeating this process and concatenating the result in a date and time formatted string.

Related

Time is set incorrectly after midnight

I use the following to get the current date/time in a more readable format:
set day=%date:~4,2%
set mth=%date:~7,2%
set yr=%date:~10,4%
set hur=%time:~0,2%
set min=%time:~3,2%
set bdate=[%day%-%mth%-%yr%]-[%hur%-%min%]
This works well and outputs something like: [02-06-2020]-[22-59]
However, after midnight the time format changes from HH:MM:SS:MS to H:MM:SS:MS. That messes up the format because it includes the colon : in the time because of the characters are shifted over by one. That results in a not useful date/time information in the log file created after midnight.
Is there any way to get the time always in the format with two digits for the hour?
Usage of dynamic variables DATE and TIME
The usage of the dynamic variables DATE and TIME with string substitutions as explained very detailed by my answer on the question What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is very fast, but has the disadvantage that the format of the date and the time string depends on region (country) configured for the account used on running the batch file.
The date can be without or with abbreviated weekday at beginning and without or with a comma appended after abbreviated weekday. The date string can be in the format year/month/day or month/day/year or day/month/year with / or . or - or   as separator. See also the Wikipedia article about date format by country.
The time can be in 12 or 24 hour format. The hour can be without or with a leading 0 on being less than 10.
It was not posted what is output on running echo %DATE% %TIME% before ten o'clock in the morning and at three o'clock in the afternoon to know the local date/time format.
It looks like it is possible to use the following code with : as separator in time string:
if "%TIME:~1,1%" == ":" (
set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[0%TIME:~0,1%-%TIME:~2,2%]"
) else (
set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[%TIME:~0,2%-%TIME:~3,2%]"
)
If the second character in time string is a colon, the condition is true and the first expression is used with 0 added left to single digit hour, otherwise the ELSE block is used with the two digit hour.
Another solution with separator in time string being either a colon or a dot or a space would be:
for /F "tokens=1,2 delims=:. " %%I in ("%TIME%") do set "Hour=0%%I" & set "Minute=%%J"
set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[%Hour:~-2%-%Minute%]"
The hour left to : or . or   is assigned to environment variable Hour with a leading zero. The minute right to : or . or   is assigned to variable Minute. The date/time string is built with taking only the last two digits of Hour to have the hour finally always with two digits in date/time string assigned to environment variable bdate.
Usage of WMIC to get current date/time
Much better would be getting current date and time region (country) independent and reformat them to wanted format using string substitutions.
A region independent date/time string can be get using Windows Management Instrumentation Command line tool WMIC.
The command line
wmic OS GET LocalDateTime /VALUE
outputs UTF-16 Little Endian encoded for example:
LocalDateTime=20200208124514.468000+060
There are two empty lines, then the line with the current local date/time in format yyyyMMddHHmmss.microsecond±UTC offset in minutes and two more empty lines.
The data can be used with a batch code like this:
#echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "DateTime=%%I"
set "bdate=[%DateTime:~6,2%-%DateTime:~4,2%-%DateTime:~0,4%]-[%DateTime:~8,2%-%DateTime:~10,2%]"
Of interest is here only the date/time string between the equal sign and the decimal point which is the reason for using for /F options tokens=2 delims==. to get just 20200208124514 assigned to loop variable I of which value is assigned next to environment variable DateTime.
The environment variable DateTime is reformatted using string substitutions to get the date/time string in format [dd-MM-yyyy]-[HH-mm] resulting in environment variable bdate being defined with [08-02-2020]-[12-45].
It would be of course possible to use bdate everywhere instead of DateTime to use just one environment variable instead of two variables.
The advantage of using WMIC to get local date/time is its independence on Windows region settings and that it is working even on Windows XP. The disadvantage is that the command execution takes a quite long time (one to two seconds on Windows XP, more than 50 ms on Windows Vista a newer Windows versions) in comparison to the usage of the DATE and TIME dynamic variables of the Windows command processor which are accessed in a few microseconds.
The command FOR has problems parsing UTF-16 LE encoded Unicode output correct. It interprets the byte sequence 0D 00 0A 00 (carriage return + line-feed) of the WMIC output wrong as 0D 0D 0A, i.e. as two carriage returns and one line-feed. This results in interpreting the last two empty lines at end of WMIC output as two lines with a single carriage return as string.
That is very often a problem because the result of set "EnvironmentVariable=%%I" is with %%I expanding to just carriage return the deletion of the environment variable already defined before with the correct value.
There are multiple solutions to work around this Unicode parsing error of command FOR. It is possible to append & goto Label to exit the loop with a jump to :Label below the FOR loop once the value is assigned to the environment variable to avoid running into this problem at all.
Another solution is using if not defined DateTime set "DateTime=%%I" with set "DateTime=" above the FOR command line to make sure the command SET is executed only once.
One more solution is the one used in this code. The name of the property and its value are output on same line because of using WMIC option /VALUE. The command FOR runs the command SET because of tokens=2 only when it could split up the current line into at least two substrings (tokens) using equal sign and dot as delimiters because of delims==.. But the wrong parsed empty lines of WMIC output is for FOR just a line containing only a carriage return and therefore has no second token. For that reason the wrongly parsed empty lines are also ignored here by the command FOR.
See How to correct variable overwriting misbehavior when parsing output? and cmd is somehow writing Chinese text as output for details on parsing problem of FOR on UTF-16 Little Endian encoded output.
Usage of ROBOCOPY to get current date/time
Another solution to get current date and time region independent is using ROBOCOPY which is available since Windows Vista and Windows Server 2003 in system directory of Windows, but is by default not available on Windows XP. robocopy.exe of Windows Server 2003 can be copied to %SystemRoot%\System32 of Windows XP to use this executable also on Windows XP, but it is not available by default on Windows XP.
ROBOCOPY is executed with invalid source directory string "C:\|" and valid destination directory string . (could be also something other valid) and argument /NJH to suppress the output of the header information.
robocopy "C:\|" . /NJH
This execution produces the error message:
2020/02/08 12:45:14 ERROR 123 (0x0000007B) Accessing Source Directory C:\|\
The filename, directory name, or volume label syntax is incorrect.
The format of current date/time at beginning of second line after the empty line is region independent.
This output can be processed with:
set "bdate="
for /F "tokens=1-5 delims=/: " %%G in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do if not defined bdate set "bdate=[%%I-%%H-%%G]-[%%J-%%K]"
FOR starts in this case one more command process in background with %ComSpec% /c and the command line between the two ' appended as additional arguments which results in Windows being installed into C:\Windows in the execution of:
C:\Windows\System32\cmd.exe /c C:\Windows\System32\robocopy.exe "C:\|" . /NJH
The first five slash or colon or space separated strings of the first non-empty line of the error message output to handle STDOUT of the background command process captured by FOR are assigned to:
G ... year
H ... month
I ... day
J ... hour
K ... minute
The five data strings are concatenated to the date/time string in the wanted format.
But FOR would run the command SET once again for the second error message line. For that reason the environment variable bdate is explicitly undefined before running FOR. The environment variable bdate is defined first with the date/time string and is next not modified anymore on FOR processing the second non-empty line because of the additional IF condition to avoid overwriting the date/time string of interest with an unwanted string.
The advantage of the ROBOCOPY solution in comparison to the WMIC solution is its much faster execution time.
Additional information
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
if /?
robocopy /?
set /?
wmic /?
wmic os /?
wmic os get /?
wmic os get localdatetime /?
PS: There are lots of other solutions to get current date/time in a specific format independent on country configured for the used account. All those alternative solutions can be found in the answers on:
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
The problem is that you're using the %DATE% and %TIME% variable values, which contain strings which are not consistent across locales, PC's, or users.
The best advice is to retrieve the information using an alternative method, for example:
#For /F "Tokens=1-5Delims=/: " %%G In (
'""%__AppDir__%Robocopy.exe" \: . /NJH /L|"%__AppDir__%find.exe" " 123""'
)Do #Set "bdate=[%%I-%%H-%%G]-[%%J-%%K]"
The method involves generating an error message from the built-in robocopy utility. We do that by asking it to copy from a target directory named : in the root of the current drive, \. An error is returned because Windows does not allow directory names containing the character :. That error message, regardless of locale, PC, or user, always outputs a line starting with the date and time strings in a known format, yyyy/MM/dd hh:mm:ss.
Examples:
2020/02/08 01:25:04 ERROR 123 (0x0000007B) Accessing Source Directory C:\:\
The filename, directory name, or volume label syntax is incorrect.
2020/02/08 01:25:04 ОШИБКА 123 (0x0000007B) Доступ к исходной папке C:\:\
‘Ё*в*ЄбЁзҐбЄ*п ®иЁЎЄ* ў Ё¬Ґ*Ё д*©«*, Ё¬Ґ*Ё Ї*ЇЄЁ Ё«Ё ¬ҐвЄҐ ⮬*.
2020/02/08 01:25:04 ERREUR 123 (0x0000007B) Copie du fichier C:\:\
La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte.
2020/02/08 01:25:04 FEHLER 123 (0x0000007B) Zugriff auf Zielverzeichnis C:\:\
Die Syntax für den Dateinamen, Verzeichnisnamen oder die Datenträgerbezeichnungist falsch.
We run our Robocopy command inside a for-loop in order that we can capture the required strings according to their known line position, format, and separator characters. We also need to account for the fact that the output consists of more than one line. To select the line, I have used the built-in find utility, and chosen to match only lines containing the string  123 as it cannot appear elsewhere in the output. Next I split the line up using the known separator characters as delimiters and choose how many delimiter separated token components to return. I choose a forward slash, /, which delimits the individual date components, a colon. :, which delimits the individual time components, and a space,  , which separates date and time from the rest of the line and each other. For your user case you only wanted five token components:
↓ ↓ ↓ ↓ ↓ delims
2020/02/08 01:25:04
↑ ↑ ↑ ↑ ↑
1 2 3 4 5 tokens
%G %H %I %J %K
The final thing I do is to put each of the components together in the required order and format, saving it as a string value within a variable named bdate. You should be able to use that value elsewhere in the script, as %bdate%, or !bdate! if delayed expansion is enabled.
To get more information of how to use a for-loop, please open a Command Prompt window and enter for /?.
set "day=%date:~4,2%"
set "mth=%date:~7,2%"
set "yr=%date:~10,4%"
set "_time=0%time%"
set "hur=%_time:~-11,2%"
set "min=%_time:~-8,2%"
set bdate=[%day%-%mth%-%yr%]-[%hur%-%min%]
You can pad time with a 0 and then do the substitution from the right side using negative numbers as the start position of the string. 1:00 would become 01-00 to match the pattern of HH-MM.
If using wmic.exe is an option, I would like to suggest this code to adjust your variable and output layout...
#echo off && setlocal enabledelayedexpansion
for /f "tokens=2delims==." %%i in ('
%__APPDIR__%\wbem\wmic OS Get LocalDateTime /value^|%__APPDIR__%findstr [0-9]')do set "dt=%%~i"
set "day=!dt:~6,2!"
set "mth=!dt:~4,2!"
set "yr=!dt:~0,4!"
set "hur=!dt:~8,2!"
set "min=!dt:~10,2!"
echo/[!day!-!mth!-!yr!]-[!hur!-!min!]
endlocal && goto :EOF
Outputs:
[08-02-2020]-[01-00]
Obs.: Consider accepting the #mofi answer

Renaming file in cmd through Teamcity declaring a variable.

I am running this script in teamcity cmd. I need to rename the file from users to users_date
I am using two %% to declare them as cmd parameters instead of Teamcity parameters.
SET TODAY=%%DATE:/=-%%
SET FNAME=User_%%TODAY%%.txt
ren User.txt %%FNAME%%.txt
When I run this through team city I get the following error:
The syntax of the command is incorrect.
Can anyone help me get the correct command?
Probably, you'd need to use % in place of each %%.
It's possible that you also need
SET TODAY=%DATE:/=-%
SET FNAME=User_%TODAY: =0%.txt
ren User.txt %FNAME%.txt
where the : =0 converts any spaces in the string today to 0s.
All depends on the exact format in which date appears. It depends on user settings, and may be in dd/mm/yy or mm/dd/yy form; with or without a dayname and may use leading-zero suppression (which I've assumed).
SET TODAY=%DATE:/=-%
SET TODAY=%TODAY:~4%
SET FNAME=User_%TODAY: =0%.txt
ren User.txt %FNAME%.txt
To remove the dayname, this form may be required - it removes the first 4 characters of the today (originally date) string.

Windows batch file timestamp to string

I am using the following simple line in my windows batch file to get the current time stamp to a String format so that I can use it later in the batch file to create a folder with same name.
set TIME_STAMP=%DATE:/=-%_%TIME::=-%
I observed that when the time is single digits, say 9:31 AM, I get the String like this:
08-10-2015_ 9.31.52.57
Notice the space between the characters _ and 9.
When the system time is say 10:31 AM, it all works fine, like
08-10-2015_10.31.52.57
Is there something I can do to make the time stamp as
08-10-2015_09.31.52.57
when I have hours in single digits?
just do this
set TIME_STAMP=%DATE:/=-%_%TIME::=-%
echo %TIME_STAMP: =0%
Probably the simpliest approach:
set "TIME_STAMP=%DATE:/=-%_%TIME::=-%"
set "TIME_STAMP=%TIME_STAMP: =0%"
Result:
==> echo "%TIME_STAMP%"
"08.10.2015_07-42-08,18"
==>

Programming in a command file

Need programming help.
Want to add current date to a command
tried this
date /t > stu.txt
call c:\Bin\MKS\sed -e 's/\//-/g' stu.txt | c:\Bin\MKS\cut -c5-14 >stu2.txt
not sure what to do here
then show current date on this command below
c:\Bin\7ZIP\7za.exe a -t7z c:\Bin\Test11-01-2013.7z #c:\Bin\TestList.txt
thanks my programming is very rusty.
Two things that may answer your question (although with you having an odd mix of unix and Windows going there, I'm not sure this will work for you):
1) The output of date can be formatted directly: for example
date +"%m-%d-%Y"
will give
11-01-2013
2) You can get the output of a command inserted into another command by using backticks:
echo the year is `date +"%Y"`
would result in
the year is 2013
You can see how you could use that to insert your date string into a command; or you can put it in an environment variable first (handy if you have more than one place where you want to insert)
set myDate=`date +"%m-%d-%Y"`
echo $myDate
results in
11-01-2013
and you can include that in a file name (or any other command):
cat file_$myDate.txt
will expand to
cat file_11-01-2013.txt
You should be able to take these concepts and map them to what you are trying to do

How to get a UNIVERSAL Windows batch file timestamp

I'm having trouble generating a timestamp in a Windows batch file, because I get diferent date formats on different Windows versions.
My machine:
>echo %date%
>Tue 11/17/2009
Friends machine:
>echo %date%
>11/17/2009
I guess there has to be some way of getting the date (11/17/2009) from both strings using for /f. I've been trying and googling and can't find the answer.
Is there another way to get a timestamp without using %date%?
Check out doff.exe. I use this a lot for getting timestamps for naming log files. From its web site:
DOFF prints a formatted date and time, with an optional date offset, (e.g -1 prints yesterday's date, +1 prints tomorrow's date). To view all the options available, execute "doff -h". I typically use this utility for renaming log files so that they include a timestamp, (see the third example below). This code should compile under Unix/Linux, as well as DOS.
Sample commands:
C:\>doff
19991108131135
With no parameters the output is the current date/time in the following format: yyyymmddhhmiss
C:\>doff mm/dd/yyyy
11/08/1999
In the above example a date format specification is given.
#echo off
for /f "tokens=1-3 delims=/ " %%a in ('doff mm/dd/yyyy -1') do (
set mm=%%a
set dd=%%b
set yyyy=%%c)
rename httpd-access.log httpd-access-%yyyy%%mm%%dd%.log
The sample batch file above shows a neat way to rename a log file based on yesterday's date. The "for" command executes doff to print yesterday's date, (the "-1" parameter specifies yesterday), then extracts each component of the date into DOS batch file variables. The "rename" command renames "httpd-access.log" to "httpd-access-[yesterday's date].log"
Also check out Microsoft's now.exe, available in the Windows Server 2003 Resource Kit Tools. One bad thing I found out (the hard way) about it is it sets the ERRORLEVEL to the number of characters printed.
Looks like this:
c:\>now
Thu May 19 14:26:45 2011
Help:
NOW : Display Message with Current Date and Time
Usage : NOW [message to be printed with time-stamp]
NOW displays the current time, followed by its command-line arguments.
NOW is similar to the standard ECHO command, but with a time-stamp.
Use VBScript if you want to get independent date time settings:
thedate = Now
yr = Year(thedate)
mth = Month(thedate)
dy = Day(thedate)
hr = Hour(thedate)
min = Minute(thedate)
sec = Second(thedate)
WScript.Echo yr&mth&dy&hr&min&sec
Unfortunately, it can't be done directly, so you need to resort to hacks like GetDate.cmd.
There are lots of VBScript and small external commandline tools available too, which isn't something I'd take a dependency on unless you're already using something of that nature in your overall system.
Personally, I'd be trying to route around it by using PowerShell which neatly sidesteps the issue completely.
You don't need VBScript. You can do it with something like this:
echo %date:~-10,2%/%date:~-7,2%/%date:~-4,4%
Source
As I have posted in here:
Batch: Timestamp to UNIX Time
What about simple 1-line long C program returning UNIX timestamp? You can retrieve value from %errorlevel% in batch script.
#include <stdio.h>
#include <time.h>
int main(void)
{
return (int) time(NULL);
}
In my test in command prompt it worked:
C:\Users\dabaran\Desktop\cs50\src\C>.\time || echo %errorlevel% && set mytstamp=%errorlevel%
1419609373
C:\Users\dabaran\Desktop\cs50\src\C>echo %mytstamp%
1419609373

Resources