Saving and restoring Date in Command Prompt - cmd

I run a command script that saves date to text file.
echo %date% > date.txt
Only problem this command saves the day in text file like so
Sun 13/08/2017
When it starts the service, I have a command to change date back
date < date.txt
I get an error
The system cannot accept the date entered.
It needs to show
13/08/2017
For this command to work
date < date.txt
I have someone gave me this command
for /F "tokens=2" %i in ('date /t') do echo %i > date.txt
it removes the day, it runs by itself.
but to run with a script it closes after it executes,
it doesnt seem to run with script.
I have other computers , I use this script and after windows update
It fixes issue; the windows update on other computer removes the day.
This computer had all windows update , but the day still displays
When you type <date> in cmd

The simple solution is using string substitution and write into the text file only the last 10 characters of the region dependent date string of built-in environment variable DATE by using this code:
>date.txt echo %DATE:~-10%
Avoid a space character before redirection operator > on writing a text with echo into a file as this space character is written as trailing space also into the file.
Sometimes it is unsafe to use echo %VariableText%>OutputFile.txt because of the variable text could end with a number in range 1 to 9 which would result in execution of the command line with 1> to 9> which means redirect handle 1 to 9 to the file instead of writing the number 1 to 9 to the file. In such cases it is advisable to specify the redirection to file at beginning of the command line before command echo as done on the command line above.
It would be also possible to use this code to save the date in format DD/MM/YYYY into the ANSI encoded text file date.txt.
#echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /Value') do set "LocalDateTime=%%I"
>date.txt echo %LocalDateTime:~6,2%/%LocalDateTime:~4,2%/%LocalDateTime:~0,4%
This code has the advantage of being independent on which region is set for the current user because the date and time string output by WMIC has always the same format. Run in a command prompt window wmic OS GET LocalDateTime /Value to see the UTF-16 encoded output of WMIC processed by command FOR line be line. The disadvantage is that this code is slower.
On setting the date back with using command DATE the region dependent date format must be known.
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 /?
set /?
wmic /?
wmic os /?
wmic os get /?
wmic os get localdatetime /?
Read also the Microsoft article about Using Command Redirection Operators.

Related

How to check if WMIC outputs an empty string or the requested original product key of Windows?

I try to use a wmic command to check for the Windows product key. I put a check to see if it is returning the Windows product key or an empty line. But the conditions IF "%%Z" == "" as well as IF [%%Z] EQU [] result always in execution of Echo Lose, i.e. key is not an empty string.
The following example is a simpler version to show the first part.
#ECHO OFF
set cmd=wmic path softwarelicensingservice get OA3xOriginalProductKey
for /f "tokens=1 skip=1" %%Z in ('%cmd% ^| findstr /r /v "^$"') do (set RESULT=%%Z)
IF "%%Z" == "" (Echo Key %RESULT%) Else (Echo Lose)
PAUSE
The string value assigned to a loop variable like Z cannot be referenced outside of the loop. The condition IF "%%Z" == "" compares always the fixed string "%Z" with the fixed string "" which are of course never equal. The condition IF [%%Z] EQU [] results first in the attempt to convert the fixed string [%Z] into a 32-bit signed integer value which fails already on first character [ and for that reason there is done next a string comparison of [%Z] with [] which are never equal too.
Some facts to know before using the code below:
The SoftwareLicensingService class is available only on Windows Vista or newer Windows client versions and on Windows Server 2008 and newer Windows server versions. This class has no property OA3xOriginalProductKey on Windows Vista and Windows Server 2008.
The SoftwareLicensingService class of Windows 7 and Windows Server 2008 R2 does not have the property OA3xOriginalProductKey too.
There is not written much about OA3xOriginalProductKey in the Microsoft documentations. There are the Microsoft documentation pages Windows 10, version 1703 basic level Windows diagnostic events and fields and An OSD task sequence doesn't continue after Windows Setup or an in-place upgrade finishes and Deploy Windows 10 Enterprise licenses with a little bit of information about OA3xOriginalProductKey. It looks like this property was introduced with OEM Activation 3.0 system used for Windows 8, Windows 8.1 and Windows 10 client versions.
There could be used the following batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "RESULT="
for /F "delims=" %%I in ('%SystemRoot%\System32\wbem\wmic.exe PATH SoftwareLicensingService GET OA3xOriginalProductKey /VALUE 2^>nul') do for /F "tokens=1* delims==" %%J in ("%%I") do set "RESULT=%%K"
if not defined RESULT echo Lose& goto EndBatch
echo Key %RESULT%
rem Other commands making use of environment variable RESULT.
:EndBatch
endlocal
pause
The usage of FINDSTR to filter out the empty lines is of no real help in case of no value output by WMIC for property OA3xOriginalProductKey because of the Unicode output of WMIC encoded with UTF-16 Little Endian with byte order mark (BOM) is processed wrong by the cmd.exe instance started in background with option /C and the specified command line as additional arguments on redirecting the output to FINDSTR with conversion to a single byte per character encoding.
The environment variable RESULT is defined in this case with a single carriage return as string assigned to the environment variable.
The workaround for this quirks of cmd.exe on processing the Unicode output of WMIC is using the option /VALUE to get output the name of property OA3xOriginalProductKey and its value on one line with an equal sign between and two empty lines above and also below the data line.
All five captured lines are processed by FOR which usually ignores empty lines completely. But there is no empty line to process by FOR because of the bug of cmd.exe interpreting the UTF-16 encoded carriage return + line-feed (0D 00 0A 00) as carriage return + carriage return + line-feed (0D 0D 0A) resulting in the four empty lines are interpreted as line with a single carriage return and the line with OA3xOriginalProductKey= at beginning as line having also an extra carriage return at the end.
For that reason each entire line with carriage return at end is assigned first to loop variable I.
One more FOR loop is used to process the string assigned to the loop variable I which results in removing the erroneous carriage return from the string value before processing it.
So for the four empty lines there is no string to process by the second FOR and so the four empty lines are indeed ignored.
The second FOR loop splits up the only line with text data into two substrings by using the equal sign as string delimiter. The first substring OA3xOriginalProductKey is assigned to loop variable J and the second substring after the equal sign is the key which is assigned to next but one loop K if there is a key at all as otherwise K is not defined and %%K on command SET executed next is replaced by an empty string.
The batch file defines with the first two lines the required execution environment completely and makes sure that the environment variable RESULT is by chance not already defined outside of the batch file with the third command line.
The IF condition after the long command line with the two FOR and the SET commands checks first if the environment variable RESULT is defined now with a real key (and not with just carriage return) to determine which ECHO command to execute next.
The long command line could be also:
for /F "delims=" %%I in ('%SystemRoot%\System32\wbem\wmic.exe PATH SoftwareLicensingService GET KeyManagementServiceMachine /VALUE 2^>nul') do for /F "tokens=2 delims==" %%J in ("%%I") do set "RESULT=%%J"
In this case just the string after the OA3xOriginalProductKey= is assigned to specified loop variable J if there is a key output by WMIC at all. Otherwise there is nothing to assign to J by second FOR and for that reason the command SET is never executed at all resulting in RESULT still not existing in list of environment variables.
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 /?
endlocal /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
wmic /?
wmic path /?
wmic path softwarelicensingservice /?
wmic path softwarelicensingservice get /?
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.

How to get the drive letter of a drive with a specific drive name on Windows? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm really new to batch scripts and I need this to automate setting up files for multiple PCs.
I have my files and a batch file stored on a flash drive.
I would like to copy (with the batch script) a file in the folder E:\IMPDoc on the flash drive to a drive on the PC with the case-insensitive drive name Files. The computers don't all have D: as the Files drive.
How can I get the drive letter of the drive named Files?
A batch file code for copying the folder IMPDoc from drive on which the batch file is stored to a drive with volume name Files is:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "skip=1" %%I in ('%SystemRoot%\System32\wbem\wmic.exe LOGICALDISK where VolumeName^="Files" GET DeviceID 2^>nul') do (
%SystemRoot%\System32\robocopy.exe "%~d0\IMPDoc" "%%I\IMPDoc" /R:1 /W:1 /NDL /NFL /NJH /NJS
goto EndBatch
)
echo ERROR: Found no drive with volume name "Files".
echo/
pause
:EndBatch
endlocal
I suggest to run first in a command prompt window the command line:
%SystemRoot%\System32\wbem\wmic.exe LOGICALDISK where VolumeName="Files" GET DeviceID
It should be displayed something like:
DeviceID
D:
What can't be seen is that the output of Windows Management Instrumentation Command is Unicode encoded using encoding UTF-16 Little Endian with byte order mark (BOM) which cause often troubles as Windows command processor is designed for processing text being character encoded with one byte per character, i.e. ASCII/ANSI/OEM encoded text. There are also trailing spaces on both lines which cannot be seen in command prompt window, too.
The FOR command line results in starting in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. For that reason it is necessary to escape the equal sign with ^ to be interpreted as literal character and not as separator between argument strings as usual with replacing = by a space character. So executed is in background with Windows installed into directory C:\Windows:
C:\Windows\System32\cmd.exe /c C:\Windows\System32\wbem\wmic.exe LOGICALDISK where VolumeName="Files" GET DeviceID 2>nul
An error output by WMIC on no drive found with case-insensitive interpreted string Files as volume name is redirected with 2>nul from handle STDERR of background command process to device NUL to suppress it.
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded wmic command line with using a separate command process started in background.
The output written by WMIC to handle STDOUT of background command process is captured by FOR and processed line by line after started cmd.exe terminated itself.
The first line is skipped because of usage of option skip=1 in addition to empty lines which are always skipped by FOR on processing captured output.
Therefore the first line processed by FOR is the second line. FOR splits up by default a line into substrings using normal space and horizontal tab characters as string delimiters and assigns just first space/tab delimited string to specified loop variable I. This default line splitting behavior is exactly what is needed here to get just drive letter and colon without the trailing spaces assigned to the loop variable I.
FOR would also ignore lines by default on which first space/tab delimited string starts with a semicolon. But there is only a single line to process which starts with a drive letter and so the default end of line option eol=; does not need to be changed in this case.
FOR executes the two commands in command block after assigning drive letter and colon to loop variable I. So ROBOCOPY copies all files in directory IMPDoc on drive with the just executed batch file to a directory IMPDoc in root of drive with volume name Files whereby the target directory is automatically created by ROBOCOPY if not already existing. Then the loop is exited with the command GOTO to continue batch file processing on the command line below the label EndBatch.
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 /?
endlocal /?
for /?
goto /?
pause /?
robocopy /?
setlocal /?
wmic /?
wmic logicaldisk /?
wmic logicaldisk get /?
See also:
Microsoft documentation for Win32_LogicalDisk class
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/

Defining a variable in a batch file not working

I have a batch file that looks like the following:
For /f "tokens=2-4 delims=/ " %a in ('date /t') do (set newdate=%c%a%b)
blat my_file_%newdate% -to test#email.com -f test_email.com
When I enter this two commands separately in a cmd window, it seems to work perfectly fine, but when placed into a batch file and ran manually, it does not work.
Open a command prompt window and run for /?. Output is the help for this command containing at top the information:
To use the FOR command in a batch program, specify %%variable instead
of %variable.  Variable names are case sensitive, so %i is different from %I.
Next I suggest to run set /? and read at least last page of output help listing the environment variable DATE.
If Command Extensions are enabled, then there are several dynamic
environment variables that can be expanded but which don't show up
in the list of variables displayed by SET.  These variable values are
computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with one of these names, then
that definition will override the dynamic one described below:
%CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
    version number.
%CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
    on this machine.
So there is perhaps no need to run in a separate command process in background with cmd.exe /C the command line date /T as done by FOR with the posted command line, capture output of this command process, and process it line by line by FOR.
Well, the format of date output by date /T or on using %DATE% depends on Windows region setting. And it was not posted what is the date format on used machine with used account. But I suppose that following works also a very little bit faster.
for /F "tokens=2-4 delims=/ " %%a in ("%DATE%") do set "newdate=%%c%%a%%b"
I suppose using only string substitution works also on your machine for your account with a date format MM/dd/yyyy or dddd, MM/dd/yyyy:
set "newdate=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%"
This last solution is some microseconds faster than the others.
There is also a region independent solution as explained in detail for example by the answer on Why does %date% produce a different result in batch file executed as scheduled task? But the region independent solution using WMIC is much slower in comparison to the usage of the dynamic environment variable DATE.
Batch variable need to have %% instead of only one
It appears you are looking for the output to be YYMMDD, if so try this:
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set newdate=%%c%%a%%b)

WHEN MAKE .bat file and run do not work WINDOWS 7

D:\> set "today=%date:~10,4%-%date:~7,2%-%date:~4,2%"
D:\> mkdir SVN_BACKUP_DUMP_TEST\%today%
D:\> CD SVN_BACKUP_DUMP_TEST\%today%
when we are make bat file this command not work
Format of date of referenced environment variable DATE depends on region setting, i.e. which country and derived from country which date format is configured for the current account. So which string is assigned to environment variable today and if that string is valid for a directory or file name depends on account specific date format.
On my computer with German set as country for my account output of echo %DATE% is 13.11.2017. So the date format is dd.MM.yyyy with point as separator, no weekday and always two digits for date and month even for a date or month less than 10.
The command line
echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2%
produces on my machine with my account and my region settings the output:
-01-1.
That is definitely not the current date in format yyyy-MM-dd.
The solution is using following batch code:
#echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "Today=%%I"
set "Today=%Today:~0,4%-%Today:~4,2%-%Today:~6,2%"
mkdir "SVN_BACKUP_DUMP_TEST\%Today%" 2>nul
cd "SVN_BACKUP_DUMP_TEST\%Today%"
This is a region independent solution. The batch code is completely explained in answer on
Why does %date% produce a different result in batch file executed as scheduled task?
What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is one more question on which answer should be read to understand the string substitutions. And run in a command prompt window set /? to get displayed the help for command SET explaining string substitution, too.

How to get the time of the last modified file in a folder using cmd

I want to get the time of the last modified file in a folder using command prompt.
For example, a folder has 10 files. In that I want the time of the recently modified file. So it should return only one entry and that should be timestamp.
Thanks in advance
This is very easy to achieve:
#echo off
for /F "delims=" %%I in ('dir * /A-D /B /O-D 2^>nul') do set "NewestFileTime=%%~tI" & goto NewestFileTime
echo There is no file in current directory.
goto :EOF
:NewestFileTime
echo Last modification time of newest file is: %NewestFileTime%
Please note that the format of the date and time string assigned to the environment variable NewestFileTime depends on Windows Region and Language settings set for the current user account respectively the account used on running this batch file.
There is also the possibility to get the last modification time of the newest file in a region-independent format, see answer on Find out if file is older than 4 hours in batch file for details.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
dir /?
echo /?
for /?
goto /?
set /?
See also single line with multiple commands using Windows batch file for an explanation of the unconditional AND operator & used in this batch code.

Resources