Batch Script for Checking time - batch-file

Is it possible to check if the time is in between two ranges and then perform an action based on it.
For eg: I want to perform an action only when the current time is not in between 11.00 PM and 6.00 A.M.
Here's what I have so far but I am unable to pin the in between part.
set "currentTime=!TIME::=!"
set "currentTime=!currentTime:,=!"
set "_bit_compare=leq"
set "compareTime=2300"
set "compareTime1=600"
(time /t | findstr /l "AM PM" || set "_bit_compare=gtr")>nul
if "!currentTime:~0,4=!" %_bit_compare% "!compareTime!" (
do somethinf
)

And just to justify my comment, using wsh, (vbscript), from a batch-file:
<!-- :
#"%__AppDir__%cscript.exe" //NoLogo "%~f0?.wsf"
#If ErrorLevel 1 Exit /B
#Rem Your Commands go below here
#Echo Within range
#Pause
#Rem Your commands end above here
#Exit /B
-->
<Job><Script Language="VBScript">
If Hour(Now())<=22 AND Hour(Now())>=6 Then
WScript.Quit(0 Mod 255)
Else
WScript.Quit(1 Mod 255)
End If
</Script></Job>
I have used Remarks to show you where you put your command or commands, and have provided two lines for demonstration purposes, (which you are free to remove once tested).

It is a few lines more to do this in a batch file but you essentially want to get the time in a standard format. You can do that by calling out to WMIC. I am just using the hour to compare. I did not see any need to use minutes based on the provided example saying it is not in between 11.00 PM and 6.00 A.M. I am using a 1 to prefix the comparison incase of leading zeros in the hour.
#echo off
set "compareTime1=23"
set "compareTime2=06"
REM GET DATE and TIME
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
SET "YYYY=%dt:~0,4%"
SET "YY=%dt:~2,2%"
SET "MM=%dt:~4,2%"
SET "DD=%dt:~6,2%"
SET "HH=%dt:~8,2%"
SET "min=%dt:~10,2%"
SET "sec=%dt:~12,2%"
IF 1%HH% LSS 1%compareTime1% IF 1%HH% GTR 1%compareTime2% (
ECHO LETS DO SOMETHING
)

This is relatively easy to write using PowerShell. If you are on a supported Windows system, PowerShell will be available. This also overcomes a myriad of problems with regional variations in cmd.exe.
$h = [int](Get-Date -Format "HH")
if ($h -le 8 -or $h -ge 23) { & notepad.exe }"
To use it in a .bat file script, you could:
powershell -NoLogo -NoProfile -Command ^
"$h = [int](Get-Date -Format "HH");" ^
"if ($h -le 8 -or $h -ge 23) { & notepad.exe }"

Related

Create a set of folders with cmd - Set a loop variable with a space

I don't know if its age or lack of practice. Either way I cannot wrap my head around this issue. I am trying to set a subroutine but the string that I am passing along are being split because of the space in string 3 and 4.
SET SubA=String1,String2,String 3,String 4
FOR %%A IN (%SubA%) DO MD "%%A"
I've tried parenthesis around the string
The <> brackets like Microsoft says to use. I have also tried this line below without success.
setlocal enableDelayedExpansion
For /F "tokens=* delims=" %%A IN (%Var%) DO MD "%%A"
Also I would love if possible could I make an list, possibly with an array. Like in Power shell I could do this. I really need to keep in the same batch file so the user could edit the list. I am aware that I could use caret but the easier I can make it for my client the better.
$Folders (
String1
String2
String 3
String 4
)
Edit: My desired result is to have this script create a set of folders like those pictured.
The simplest pure batch-file solution that doesn't require trickery is to use for's ability to enumerate space-separated tokens.
For this to work as intended, tokens that themselves contain spaces must be double-quoted:
#echo off & setlocal
:: Space-separated list of folder names, with names that contains
:: spaces themselves double-quoted.
SET SubA=String1 String2 "String 3" "String 4"
:: Loop over the list elements and create a directory for each.
FOR %%A IN (%SubA%) DO MD %%A
As Compo's helpful answer implies, you could actually pass this list to a single invocation of
MD: MD %SubA%
Unfortunately, as far as I know, batch files do not offer a convenient way to define lists in a one-item-per-line format.
However, you could provide the list of names via an external file, with each name on its own line (no double-quoting needed), which can then be parsed with for /f; e.g.:
#echo off & setlocal
:: Determine the full path of the file "names.txt"
:: located in the same folder as this batch file.
set "nameList=%~dp0names.txt"
:: Loop over all names in the file and call `md` with each.
for /f "usebackq delims=" %%n in ("%nameList%") do md "%%n"
And input file names.txt would then contain something like:
String1
String2
String 3
String 4
The simplest way to 'make' your directories is probably like this:
Set "SubA=String1,String2,String 3,String 4"
MD "%SubA:,=" "%" 2>NUL
As for working with the initial variable, and using it array like, you could do it like this:
#Echo Off & SetLocal EnableExtensions EnableDelayedExpansion
Set "SubA=String1,String2,String 3,String 4"
For /F "Delims==" %%G In ('"(Set Index[) 2>NUL"') Do Set "%%G="
Set "i=0"
Set "Index[!i!]=%SubA:,=" & Set /A i += 1 & Set "Index[!i!]=%"
(Set Index[) 2>NUL && Pause
Or you could do it like this:
#Echo Off & SetLocal EnableExtensions EnableDelayedExpansion
Set "SubA=String1,String2,String 3,String 4"
For /F "Delims==" %%G In ('"(Set Index[) 2>NUL"') Do Set "%%G="
Set "i=-1"
For %%G In ("%SubA:,=","%") Do (Set /A i += 1
Set "Index[!i!]=%%~G")
(Set Index[) 2>NUL && Pause
Here is another way to create the directories using the PowerShell that is already on your system if it is still supported by Microsoft. When you are satisfied that the correct directories will be created, remove the -WhatIf from the mkdir command.
SET "SubA=String1,String2,String 3,String 4"
powershell -NoLogo -NoProfile -Command ^
"'%SubA%'.split(',') | ForEach-Object { mkdir $_ -WhatIf | Out-Null }
A better way would be to test to see if the directory already exists before trying to create it.
SET "SubA=String1,String2,String 3,String 4"
powershell -NoLogo -NoProfile -Command ^
"'%SubA%'.split(',') | ForEach-Object {" ^
"if (-not (Test-Path -Path $_)) { mkdir $_ | Out-Null }" ^
"}"

Date Output error in Batch Script only on the 8th

I current run the below script to get the current day minus 1 and the current month. It works great for all days and month except for the 8th of every month and August of every year. I have to change the script to setting it manually for August. Does anyone know why and is there a fix.
SET m=%date:~4,2%
SET /A m -= 1
SET m=0%m%
REM ****** SET m=08 this was used because the date was not right ******
REM SET m=08
SET currMon=%date:~4,2%/%date:~10,4%
REM ****** SET PriorMon=12/2017 this was used for Year End because the date was not right ******
REM SET PriorMon=08/2018
SET PriorMon=%m:~-2%/%date:~10,4%
This is a hybrid vb/batch script. It is a proper way to get the date -1 or whatever amount of days you want:
#echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\*%~n0.vbs"
set "yyyy=%result:~0,4%"
set "mm=%result:~4,2%"
set "dd=%result:~6,2%"
set "final=%dd%-%mm%-%yyyy%"
echo %final%
I simply echo the final result here which as far as today's date goes (for me as it is the 7th) should echo 06-09-2018
You can change the format of %final% as you please to suit your date..
Proper date calculatons in pure batch are possible but tedious.
Your approach relies on possibly unknown locale/user settings dependant date format.
From Win7 on Powershell is available as a tool:
On cmd line:
For /f "usebackq" %A in (`powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"`) Do Set Yesterday=%A
In a batch file:
For /f "usebackq" %%A in (`
powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"
`) Do Set Yesterday=%%A
Echo Yesterday=%Yesterday%
Modify the format string to your liking:
dd = day 2 places
MM = month 2 places
yyyy = year 4 places
Other characters have to be escaped with a backslash.

Batch Script Timestamp Variable without spaces YYYY-MM-DD-HH-MM-SS

I've created a timestamp variable in a batch script like so...
set TIMESTAMP=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%-%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%
There is an issue though when the HH is only a single digit I get...
YYYY-MM-DD- 2-MM-SS
instead of
YYYY-MM-DD-02-MM-SS
How do I consistently generate the timestamp without spaces?
set "timestamp=%timestamp: =0%"
replaces spaces with zeroes.
See set /? from the prompt for documentation.
Don't use locale/user settings dependent date time variables but wmic:
#Echo off
For /f "delims=." %%A in (
'wmic os get LocalDateTime^|findstr ^^20'
) Do Set DT=%%A
Set "TIMESTAMP=%DT:~0,4%-%DT:~4,2%-%DT:~6,2%-%DT:~8,2%-%DT:~10,2%-%DT:~12,2%"
Set TimeStamp
Sample output:
> SO_45465890.cmd
TIMESTAMP=2017-08-02-18-42-07
Or use PowerShell and let it do the formatting:
#Echo off
For /f %%A in ('powershell -NoP -C "get-date -f \"yyyy-MM-dd-HH-mm-ss\""') Do Set TimeStamp=%%A
Set TimeStamp

Second instance of batch loop does not run

I am trying to create a DOS batch script on my Windows 7 machine. I want to execute file 123456.bat, which contains the following command and parameters:
call **startSelenium.bat** 55 someSuiteName suite-someSuite.html development 1 1 10 10
That script calls into the startSelenium.bat script below:
Setlocal EnableDelayedExpansion
SET TimeStamp=
FOR /f "tokens=1-4 delims=/ " %%i in ("%date%") do set datestr=%%l%%j%%k
FOR /f "tokens=1-4 delims=.: " %%i in ("%time%") do set timestr=%%i%%j%%k%%l
SET TimeStamp=%datestr%%timestr%
set a=2
set b=0
set /a c=%a%+%b%
FOR /l %%t IN (1, 1, %c%) do (
call :SEARCHPORT %%t
echo %startPort%
Start java -jar C:\Selenium\2\selenium-server-standalone-2.47.1.jar -port %startPort% -singleWindow -userExtensions C:\selenium\2\user-extensions.js -firefoxProfileTemplate "c:\selenium\2\ffprofiles\2rc" -htmlSuite "*chrome" "https://www.google.com" "Z:\selenium\2\environment\%4\suites\%3" "u:\results\%4\result-%1-%computername%-1234-%TimeStamp%.htm"
timeout /t 10
)
GOTO :EOF
:SEARCHPORT
netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
set /a startPort +=1
GOTO :SEARCHPORT
) ELSE (
set freePort=%startPort%
echo %startPort%
GOTO :EOF
When I run the script, the first instance of the java applications runs with a free Windows port that the SEARCHPORT subroutine found; however, the second instance pops up and quits immediately. I suspect the code is using the same variable from the first time it went through the FOR loop instead of getting a new unused port number.
What am I doing wrong? I copied various parts of this code from other sources. I am obviously a nube, so plain English would be helpful. :)
You have got an delayed expansion issue.
You already enabled delayed expansion, but you don't use it. You have to replace %startPort% with !startPort! inside your for /l loop.

Batch Script: Search thru multiple files for part of an IP address and log it

I have multiple TraceRT log files containing 30 hops. I'm only looking for similar IP (ex. 192.168.1) and would like to log it on one file with:
1) Successful: %IP% found in %Filename%
2) Fail: Specified IP not found in %Filename%
I'm trying to use:
rem************************************************************
:START
# ECHO OFF
rem US date
set YEAR=%DATE:~10,4%
set MONTH=%DATE:~4,2%
set DAY=%DATE:~7,2%
rem US hour
set HOUR=%TIME:~0,2%
set MIN=%TIME:~3,2%
set SEC=%TIME:~6,2%
set HUNDREDS=%TIME:~9,2%
set HOURMIN=%HOUR%%MIN%
rem Make sure that hour has two digits
IF %HOUR% GEQ 10 goto twoh
set HOUR1=%TIME:~1,1%
set TWOHOUR=0%HOUR1%
goto fulltid
:twoh
set TWOHOUR=%HOUR%
:fulltid
set FULLTIME=%TWOHOUR%'%MIN%'%SEC%'%HUNDREDS%
set FTIME=%TWOHOUR%:%MIN%:%SEC%
#echo off & setLocal EnableDELAYedeXpansion
findstr /m "192.168.1" *.txt > FILENAME
echo on
for /f "tokens=*" %%a in (*.txt ^| find "192.168.1") do (
IF %%a neq %%b (
echo Suscessful: %%a %FILENAME% >> Log%YEAR%%MONTH%%DAY%.txt
) ELSE (
echo Fail: Specified IP not found in %FILENAME% >> Log%YEAR%%MONTH%%DAY%.txt
)
)
goto START
rem************************************************************
You have specified an invalid pipe | find. You cannot pipe (a) text file(s) into a command.
Either provide the file(s) as argument(s) to find, or use redirection (this works for a single file only but not for multiple ones nor */? patterns though).
You are using for /f not correctly.
It looks as if you wanted to parse the output of find. To accomplish that, but you must enclose the command within single-quotes '. Type for /? and see the help text for more details.
The following line of code should work:
for /f "tokens=*" %%a in ('find "192.168.1" *.txt') do (
To get current date and time, I strongly recommend to read variables %DATE% and %TIME% once only and within a single line! Otherwise you might run into problems, especially concerning the fractional seconds, which might not be equal between consecutive expansions.
To ensure %HOUR% to have two digits, you simply need to use set HOUR=0%HOUR% then set HOUR=%HOUR:~-2%.
Since a one-digit %HOUR% is prefixed by a space here, you can have it even simpler (thanks for your comment, #Stephan!) by just replacing the space by a zero: set HOUR=%HOUR: =0%.

Resources