Windows command line dates - windows

I have an hard coded windows command line with dates (from: yesterday until today)
I want to replace the hard coded dates with an expression like date.add(-1) for yesterday.
I know how to get current date: %date:~10,4%-%date:~4,2%-%date:~7,2%
but how can I do this for yesterday?
thanks!

You can do exactly that in cmd using PowerShell. PowerShell is available for Windows from Windows 7. Are you running Windows 98 or something earlier?
FOR /F %a IN ('powershell -NoProfile -Command "(Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"') do (SET "YD=%a")
ECHO %YD%
Here is a .bat file equivalent.
#ECHO OFF
FOR /F %%a IN ('powershell -NoProfile -Command "(Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"') do (SET "YD=%%a")
ECHO %YD%
EXIT /B 0

Related

How to get M-D-YY format for batch? [duplicate]

This question already has answers here:
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
(30 answers)
Closed last year.
to follow up on the last solution in this link https://www.windows-commandline.com/get-date-time-batch-file/
I know there's no windows CMD format with this but I've tried to batch replace and arrays apparently don't have good solutions if you Google for an answer since most of the time people find and replace things in files I keep getting those answers.
If you are on a supported Windows system, powershell.exe will be available.
C:>#FOR /F "delims=" %A IN ('powershell.exe -NoLogo -NoProfile -Command Get-Date -Format 'M-d-yy'') DO #(SET "THEDATE=%~A")
C:>echo %THEDATE%
1-21-22
If this is in a .bat file script, double the PERCENT SIGN characters on the loop variable. %%A
If you want a pure batch solution, wmic provides a few date-related strings without leading zeroes:
#echo off
setlocal
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set "_%%x"
set "Mydate=%_Month%-%_Day%-%_Year%"
echo %mydate%
echo maybe also useful sometimes:
set _

How to get the content of a text file using command FOR on a batch file

I have a text file where the contents have a lot of NUL or spaces between data:
[nul][nul][nul][nul]Name [nul][nul][nul][nul][nul][nul]surname
The data inside of the text file is always different.
I have searched and tested many similar questions using for /F "usebackq delims=" %%a in ("%file%") do echo %%a and similar commands, but i always get empty results.
Please can anyone help?
If you truly have a text file with, for example, the following content:
External image link
And you just want to omit the NUL characters as part of a normal For /F loop file read, then you could ask powershell for help from your batch-file:
#For /F "Delims=" %%G In (
'%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe ^
-Nologo -NoProfile -Command "(Get-Content 'sourcefile.txt')" ^
" -replace '\x00',''"') Do #Echo(%%G
#Pause
I have split that long line up into multiple for easier reading, but you could also have it as a single line batch-file:
#(For /F "Delims=" %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -Nologo -NoProfile -Command "(Get-Content 'sourcefile.txt') -replace '\x00',''"') Do #Echo(%%G) & Pause
And to do it in simple terms directly from the Command Prompt cmd:
For /F "Delims=" %G In ('powershell -NoP "(GC 'sourcefile.txt') -replace '\x00',''"') Do #Echo(%G
[Edit /]
If you wanted to add a single comma, between those two specific words in the exact example you provided, and which I used in my linked image above, then yes, it would be possible.
For example you could do it within the PowerShell part, by changing:
-replace '\x00','' to -replace ' ',', ' -replace '\x00',''
Or, you could do it by changing the For loop option:
"Delims=" to "Tokens=1*"
and then change either:
#Echo(%%G, or #Echo(%G
to:
#Echo(%%G, %%H or #Echo(%G, %H respectively.

Calling `ver` in FOR expression from a batch file freezes cmd in Windows 10

I am trying to check OS version from a batch file and I am running into the following problem.
The line
FOR /F "tokens=*" %%i IN ('ver') DO (SET var=%%i)
will freeze the cmd when executing from a batch file while the command ver by itself (in the same batch file) executes without problem. (ver has the following output.)
Microsoft Windows [Version 10.0.18362.356]
What could be wrong in the expression?
To avoid recursion and unexcpected FOR/F behaviour, you can use a guard in the AutoRun batch script (like the variable based one shown by #sst).
#echo off
setlocal EnableDelayedExpansion
set "cmd=!cmdcmdline!"
if "!cmd!" == "!cmd:/=!" (
REM *** Define doskey macros
2>nul (
doskey npp="%ProgramFiles(x86)%\notepad++\notepad++.exe" $*
)
endlocal
REM *** Set additional variables
REM *** Change to a default directory
cd c:\temp
)
As it is mentioned in the comments beneath your question, the apparent freezing is caused by fact that you've setup that cmd statement to be executed through the cmd's AutoRun registry setting: [HKEY_LOCAL_MACHINE/HKEY_CURRENT_USER]\Software\Microsoft\Command Processor\AutoRun
When using for /F to capture the output of another command/program, an implicit instance of cmd will be invoked to execute the command/program referenced in the for's IN clause.
When there is an entry in the cmd's AutoRun registry setting that implicit cmd instance will in turn execute the AutoRun commands, And in your case that AutoRun command will execute another instance of cmd through the for /F command. You see that where it is going: infinite chain of nested cmds will be launched until it exhaust system resources.
To avoid trapping in the infinite loop, you need to guard the statement from executing more than once
Here is one method which is written as a batch file:
:: This batch file can be safely executed through cmd's Autorun
#echo off
if not defined WinVer (
set "WinVer=AutorunGuard"
for /F "tokens=1* delims=[" %%A in ('ver') do (
for /F "tokens=2 delims=] " %%V in ("%%B") do set "WinVer=%%V"
)
)
I've also extended the method of extracting windows version to include only the version number, not the whole version string which is return by ver
It can be used to extract version number for windows versions from Windows 2000 to Windows 10
If you don't want to use a batch file, and prefer to put the statement strait in to AutoRun registry setting, this one-liner can be used instead:
#if not defined WinVer set "WinVer=AutorunGuard" & for /F "tokens=1* delims=[" %A in ('ver') do #for /F "tokens=2 delims=] " %V in ("%B") do #set "WinVer=%V"
Don't name your batch file as ver.bat;
Rename it for example as CMD_Version.bat
#echo off
FOR /F "tokens=*" %%i IN ('ver') DO (SET var=%%i)
echo %var%
pause
You could get the information from Win32_OperatingSystem using wmic:
#For /F "EOL=V" %%A In ('WMIC OS Get Version')Do #For /F "Tokens=*" %%B In ("%%A")Do #Set "var=%%B"
or powershell:
#For /F %%A In ('"PowerShell (GWMI Win32_OperatingSystem).Version"')Do #Set "var=%%A"
You could also do the same using wsh, i.e. leveraging one of the vbscript or jscript engines.
An alternative, though not as robust as using WMI, is to get the information from the registry.
#Echo Off
Set "RKey=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Set "KVal=\<CurrentBuildNumber\> \<CurrentVersion\> \<ProductName\> \<UBR\>"
For /F Tokens^=1-2* %%A In (
'^""%__AppDir__%reg.exe" Query "%RKey%" 2^>NUL^|"%__AppDir__%findStr.exe" /I "%KVal%"^"'
)Do #If "%%A"=="UBR" (Set /A %%A=%%C)Else Set "%%A=%%C"
Echo(%ProductName% %CurrentVersion%.%CurrentBuildNumber%.%UBR%
Pause
Note: I do not think that UBR is a pre Windows 7 entry, so in those cases you'd simply have a trailing period in your output.

How to print PDF documents in batch mode? (using Windows Task Scheduler)

I am trying to print in batch mode each of the PDF files contained in a Windows directory by writing a batch script which uses Adobe Acrobat Reader to filter them out, but I haven't succeeded in the <'SEVERAL-OPTIONS'> section as follows:
#echo off
SETLOCAL EnableDelayedExpansion
SET WRK_PATH="c:\a\b"
SET PDF_READER_PATH="c:\d\e"
...
cd !WRK_PATH!
for /F "tokens=*" %%a in ('dir /b/a-s *.pdf') do (
#echo File: %%~fa
**<SEVERAL-OPTIONS>**
ping localhost -4 -n 10 >nul
)
Where < SEVERAL-OPTIONS> have been:
1 - cmd /C "c:\d\e\AcroRd32.exe" /t %%~fa printerQ
2 - start "" "C:\d\e\AcroRd32.exe" /t %%~fa printerQ
3 - start /b "" "C:\d\e\AcroRd32.exe" /t "%%~fa" "printerQ"
4 - PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\d\e\AcroRd32.exe'" ' /t c:\a\b\file1.pdf printerQ'
Although some of them works fine having a Windows session active, they cannot when they are scheduled as Task.

PowerShell command in batch script condition

I need a line of script that does something like this:
if (results from PowerShell command not empty) do something
The PowerShell command is basically
powershell -command "GetInstalledFoo"
I tried if (powershell -command "GetInstalledFoo" != "") echo "yes" but get the error -command was unexpected at this time. Is this possible to accomplish? This command will eventually be run as the command to cmd /k.
BartekB's answer works as long as at least one line of output does not start with the FOR /F eol character (defaults to ;) and does not consist entirely of delimiter characters (defaults to space and tab). With appropriate FOR /F options it can be made to always work.
But here is a simpler (and I believe faster) way to handle multiple lines of output that should always work.
for /f %%A in ('powershell -noprofile -command gwmi win32_process ^| find /v /c ""') do if %%A gtr 0 echo yes
Another alternative is to use a temp file.
powershell -noprofile -command gwmi win32_process >temp.txt
for %%F in (temp.txt) if %%~zF gtr 0 echo yes
del temp.txt
Third way: set an environment variable from your PowerShell script and test it in your batch file?
I guess if won't be the best solution for that. I would use for /f instead:
for /f %R in ('powershell -noprofile -command echo foo') do #echo bar
That should give you 'bar', while this:
for /f %R in ('powershell -noprofile -command $null') do #echo bar
... should not. In actual .bat/ .cmd file you have to double % (%%R)
or better yet, if you don't want to many bar's returned...:
(for /f %R in ('powershell -noprofile -command gwmi win32_process') do #echo bar) | find "bar" > nul && echo worked

Resources