There is a text file that stores a log of processed files in the following format:
Name: kn-25.txt Date: 01.02.2013 Time: 14:50
The task is to write a batch file which will make a selection from this file for a given month (mm) and year (yyyy) into the file result.txt.
#echo off
chcp 1251 >nul
setlocal EnableDelayedExpansion
echo Введіть початковий файл:
set /p in_file=%~nx1
if not exist %in_file% goto end
del D:\result.txt
set /a count=0
set /a con=0
set /a min=101
set /p month=Введіть місяць:
if [%month%] == [] goto end
set /p year=Введіть рік:
if [%year%] == [] goto end
goto start
:start
if count equ 0 (
set /a con=0
) else (
set /a con=0-!count!
)
for /f "tokens=*" %%i in (%in_file%) do (
for /f "tokens=1-6" %%a in ("%%~i") do (
for /f "delims=. tokens=1-3" %%u in ("%%~d") do (
if "%%v"=="%month%" if "%%w"=="%year%" (
set /a con=!con!+1
if "%%u" leq "!min:~-2!" (
set /a min1=!min!-1
if "%%u" neq "!min1:~-2!" (
set /a count=!count!+1
echo !count!. %%i>>D:\result.txt
)
)
)
)
)
)
if %con% neq %count% (
set /a min=!min!+1
goto start
) else (
type D:\result.txt
echo
#pause
endlocal
exit /B
)
:end
echo Ви не ввели параметр!
echo
#pause
endlocal
exit /B
I wrote this code, but got an error:
Cannot find the file Name:.
Any suggestions?
Note: information in the generated file must be sorted by date
Example:
Initial file content:
Name: kn-25.txt Date: 07.03.2013 Time: 14:50
Name: kn-26.txt Date: 02.03.2013 Time: 23:50
Name: MyFil.txt Date: 03.08.2012 Time: 12:00
Name: ca-21.txt Date: 28.03.2013 Time: 01:00
Name: ca-25.txt Date: 01.30.2012 Time: 10:05
Input: 03.2013
Output:
Name: kn-26.txt Date: 02.03.2013 Time: 23:50
Name: kn-25.txt Date: 07.03.2013 Time: 14:50
Name: ca-21.txt Date: 28.03.2013 Time: 01:00
a slightly different approach (slower than the other ones, but working as intended):
#echo off
setlocal EnableDelayedExpansion
set in_file=t.txt
set month=03
set year=2013
(for /l %%a in (100,1,131) do (
set "day=%%a"
findstr "!day:~-2!.%month%.%year%" %in_file%
))>result.txt
For sorting we ignore the first 22 characters sort command.
#echo off
chcp 1251 >nul
setlocal EnableDelayedExpansion
echo Введіть перший параметр:
set /p in_file=%~f1
if not exist %in_file% goto end
set /p month=Введіть місяць:
if [%month%] == [] goto end
set /p year=Введіть рік:
if [%year%] == [] goto end
findstr /C:"%month%.%year%" %in_file% | sort /+22 > D:\result.txt
type D:\result.txt
pause
exit /B
:end
echo Ви не ввели параметр!
pause
exit /B
We can use findstr /O if we want an offset on each line.
If you are on a supported Windows machine, it will have PowerShell on it. Here is one way to do it. This assumes that the date is in DD.MM.YYYY format.
Since it has already parsed out the date and time with a regex, it creates a [DateTime] to associate with the log file line. It then uses this [DateTime] to sort the file, but only outputs the log file line.
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,Position=0)]
[string]$LogFile
,[Parameter(Mandatory=$true,Position=1)]
[int]$Year
,[Parameter(Mandatory=$true,Position=2)]
[int]$Month
)
Get-Content -Path $LogFile |
ForEach-Object {
if ($_ -match 'Name: .* Date: ((\d*).(\d*).(\d*)) Time: ((\d*):(\d*))') {
#$Matches
$fday = [int]$Matches[2]
$fmonth = [int]$Matches[3]
$fyear = [int]$Matches[4]
$fhour = [int]$Matches[6]
$fminutes = [int]$Matches[7]
if (($fmonth -eq $Month) -and ($fyear -eq $Year)) {
[PSCustomObject]#{
Line = $_
Timestamp = Get-Date -Year $fyear -Month $fmonth -Day $fday `
-Hour $fhour -Minute $fminutes -Second 0
}
}
}
} |
Sort-Object -Property Timestamp |
ForEach-Object { $_.Line }
Invoke it using the following command. If you do not provide the parameters, PowerShell will prompt for them. That is like using SET /P in a cmd.exe bat file script.
.\logparse.ps1 -LogFile '.\logparse.in.txt' -Year 2013 -Month 2
If you must run it from a cmd.exe shell, use:
powershell -NoLogo -NoProfile -File ".\logparse.ps1"
The following code uses a temporary file containing the lines from the input file filtered by the given date information (month and year), but with each line prefixed by year, month and day as well as the time value, which allows easy alphabetic sorting that is fine for your fixed-width date/time formats:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "IN_FILE=%~1"
set "OUT_FILE=D:\result.txt"
set "TMP_FILE=%TEMP%\%~n0_%RANDOM%.tmp"
set "MONTH=03"
set "YEAR=2013"
rem /* Filter lines for given month and year, then write them
rem to temporary file, preceded by year, month, date and `:`: */
> "%TMP_FILE%" (
for /F usebackq^ delims^=^ eol^= %%L in ("%IN_FILE%") do (
for /F "tokens=3-5 delims=:" %%D in ("%%L") do (
for /F "tokens=1-3 delims=. " %%A in ("%%D") do (
if "%%B" == "%MONTH%" if "%%C" == "%YEAR%" (
echo(%%C%%B%%A%%E%%F:%%L
)
)
)
)
)
rem /* Sort content of temporary file, remove prefix
rem up to the (first) `:` and write to result file: */
> "%OUT_FILE%" (
for /F "tokens=1* delims=:" %%E in ('sort "%TMP_FILE%"') do (
echo(%%F
)
)
rem // Clean up temporary file:
del "%TMP_FILE%"
endlocal
exit /B
Related
I would like to edit the following batch code in order to create a folder with every working day of the year and skip saturday and sunday (i guess it should create 5 consecutive days and skip the next 2)
I would also like the batch file to
skip creating folders for each month(a january folder, a february folder etc) and have all days of the year in the same folder.
add two extra folders in each day folder with 'morning' and 'afternoon'
Ex:
C:\Users\alex\Desktop\2022\1 Jan\Morning
C:\Users\alex\Desktop\2022\1 Jan\Afternoon
all the way to
C:\Users\alex\Desktop\2022\31 Dec\Morning
C:\Users\alex\Desktop\2022\31 Dec\Afternoon
(it would not create 31 dec folder because thats a saturday)
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\years"
SET /p year=### Enter Year [e.g. 2014]:
IF NOT DEFINED year GOTO :EOF
SET year=%year:,=%
IF %year% lss 100 SET /a year=2000+year
IF %year% gtr 1901 IF %year% lss 2099 GOTO generate
ECHO year entered out of range 1901..2099
GOTO :eof
:generate
MD "%sourcedir%"
SET /a feb=year %% 4
IF %feb%==0 (SET "feb=02,February,29") ELSE (SET "feb=02,February,28")
PUSHD "%sourcedir%"
MKDIR %year%
CD %year%
FOR %%a IN ("01,January,31" "%feb%" "03,March,31" "04,April,30" "05,May,31" "06,June,30" "07,July,31" "08,August,31" "09,September,30" "10,October,31" "11,November,30" "12,December,31") DO (
FOR /f "tokens=1-3delims=," %%b IN (%%a) DO (
SET "month=%%c"
SET "month=!month:~0,3!"
MKDIR %%b_%%c
pushd %%b_%%c
FOR /l %%q IN (1,1,%%d) DO MD %%q-!month!-%year%
popd
)
)
popd
GOTO :EOF
This is a very simple task when you use the right method and formulae:
#echo off
setlocal EnableDelayedExpansion
set "i=0"
for %%a in (Mon Tue Wed Thu Fri Sat Sun) do (
set "DayOfWeek[!i!]=%%a"
set /A i+=1
)
set /P "Year=Enter year: "
set /A "leap=28+^!(Year%%4)*^!^!(Year%%400)"
set "MonthNameDays=Jan:31 Feb:%leap% Mar:31 Apr:30 May:31 Jun:30 Jul:31 Aug:31 Sep:30 Oct:31 Nov:30 Dec:31"
rem Get Julian Day Number of Jan/01 of given year
rem adjusted as multiple of day of week: JDN % 7 = 0..6 for Mon..Sun
rem Reference: http://www.hermetic.ch/cal_stud/jdn.htm#comp
set /A "JDN=(1461*(Year+4799))/4+4037/12-(3*((Year+4899)/100))/4-1, MM=100"
for %%a in (%MonthNameDays%) do for /F "tokens=1,2 delims=:" %%x in ("%%a") do (
set /A MM+=1
ECHO md "!MM:~1! %%x"
ECHO pushd "!MM:~1! %%x"
for /L %%d in (1,1,%%y) do (
set /A "JDN+=1, DOW=JDN%%7, DD=100+%%d"
if !DOW! lss 5 (
for %%w in (!DOW!) do (
ECHO md "!DD:~-2! !DayOfWeek[%%w]!"
)
)
)
ECHO popd
)
I focused on the core point of generate folders for Mon..Fri days of week, so I not included some minor details, like generate Morning/Afternoon folders. Also, I just echoed the "MD" commands...
As per my earlier comment, the following batch file gets the assistance of PowerShell:
#Echo Off
SetLocal EnableExtensions
:AskYear
ClS
Set "YYYY="
Set /P "YYYY=Please enter a four digit year from 1900 to 2099 incl.>"
Set YYYY 2>NUL|%SystemRoot%\System32\findstr.exe /R^
"^YYYY=19[0123456789][0123456789]$ ^YYYY=20[0123456789][0123456789]$" 1>NUL || GoTo AskYear
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile^
"$beginningOfYear = Get-Date -Year %YYYY% -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0;"^
"$endOfYear = ($beginningOfYear).AddYears(1).AddSeconds(-1);"^
"While ($beginningOfYear -LE $endOfYear) {"^
" $beginningOfYear = ($beginningOfYear).AddDays(1);"^
" If ($beginningOfYear.DayOfWeek -GT 0) {"^
" If ($beginningOfYear.DayOfWeek -LT 6) {"^
" $children=#('Morning','Afternoon');"^
" ForEach ($i In $children) {"^
" md \"$($beginningOfYear.ToString('yyyy\\d MMM'))\$i\"}}}}"
The above example assumes that your culture/locale settings use the first day of the week 0 as the last day of the weekend, and the 6 as the first day of the weekend. If your culture/locale settings use 6 and 5 for those two days respectively, then you'd simply change the code accordingly:
#Echo Off
SetLocal EnableExtensions
:AskYear
ClS
Set "YYYY="
Set /P "YYYY=Please enter a four digit year from 1900 to 2099 incl.>"
Set YYYY 2>NUL|%SystemRoot%\System32\findstr.exe /R^
"^YYYY=19[0123456789][0123456789]$ ^YYYY=20[0123456789][0123456789]$" 1>NUL || GoTo AskYear
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile^
"$beginningOfYear = Get-Date -Year %YYYY% -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0;"^
"$endOfYear = ($beginningOfYear).AddYears(1).AddSeconds(-1);"^
"While ($beginningOfYear -LE $endOfYear) {"^
" $beginningOfYear = ($beginningOfYear).AddDays(1);"^
" If ($beginningOfYear.DayOfWeek -LT 5) {"^
" $children=#('Morning','Afternoon');"^
" ForEach ($i In $children) {"^
" md \"$($beginningOfYear.ToString('yyyy\\d MMM'))\$i\"}}}"
Not pure batch, but you can use powershell to help a bit.
#echo off
set "sourcedir=U:\years"
set /p year=### Enter Year [e.g. 2014]:
echo 0..365 ^| %% { $date = Get-Date "%year%-01-01";$date = $date.AddDays($_).ToString("dddd dd MMMM yyyy");Write-Host $date"" }>tmp.ps1
for /F "tokens=1-4*" %%a in ('powershell .\tmp.ps1') do (
if "%%~d" == "2022" if not "%%a" == "Saturday" if not "%%a" == "Sunday" (
echo mkdir "%sourcedir%\%%c %%d\%%a %%b\Morning"
echo mkdir "%sourcedir%\%%c %%d\%%a %%b\Afternoon"
)
)
del /Q tmp.ps1
PS!! you don't have to use the temp file at all, I just don't have the time now to do all the escaping of special characters, but it will help you in the right direction, if you can use hybrids.
You can move the year/month/days around as you please. If you want short Month and Day (Dec, Mon instead of December Monday) change the format in the powershell portion:
echo 0..365 ^| %% { $date = Get-Date "%year%-01-01";$date = $date.AddDays($_).ToString("ddd dd MMM yyyy");Write-Host $date"" }>tmp.ps1
Result:
I would like to list all available, removable hard drives in a batch script and continue to work with the chosen option. I know there are options like
wmic logicaldisk get caption,volumename
to list the hard drives and
SET /P M=Type 1 or 2 then press ENTER:
IF %M%==1 GOTO One
IF %M%==2 GOTO Two
to create a menu. But how do I store the volumes in variables and list them in a menu?
Something like:
Choose from list:
1) D:\Harddrivename1
2) E:\Harddrivename2
Enter option: 2
Any help is appreciated!
Here's a function that'll let you create an array of drives that are not of type 3 (fixed):
rem // populates arrayname, arrayname.length, and arrayname.ubound
:getRemovableDrives <arrayname>
rem // unset array if exists
for /f "delims==" %%I in ('2^>NUL set %~1') do set "%%~I="
setlocal enabledelayedexpansion
set /a %~1.length = 0, %~1.ubound = -1
rem // note: nested for /f loops convert UCS-2 encoded WMI results to ANSI
for /f "skip=2 delims=" %%# in (
'wmic logicaldisk where "DriveType <> 3" get caption^,volumename /format:csv'
) do for /f "tokens=2,3 delims=," %%I in ("%%~#") do (
set "%~1[!%~1.length!].caption=%%~I"
set "%~1[!%~1.length!].volumename=%%~J"
set /a %~1.ubound = %~1.length, %~1.length += 1
)
rem // Trick to make private variables public
for /F "delims=" %%I in ('set %~1') do (
if defined %~1.ubound endlocal
set "%%~I"
)
exit /b
Here's a full example illustrating how to use the function:
#echo off & setlocal enabledelayedexpansion
:begin
call :getRemovableDrives drives
if %drives.length% equ 0 (
echo No removable drives found.
exit /b 1
)
set choices=
echo Removable drives:
echo;
for /L %%I in (0, 1, %drives.ubound%) do (
set "choices=!choices!%%I"
echo(%%I^) !drives[%%I].caption! (!drives[%%I].volumename!^)
)
echo(X^) exit
set "choices=%choices%x"
echo;
choice /C %choices% /N /M "Press a number (or X to quit): "
set /a choice = %ERRORLEVEL% - 1
if not defined drives[%choice%].caption exit /b 0
echo You chose !drives[%choice%].caption! (!drives[%choice%].volumename!^)
goto :begin
goto :EOF
rem // populates arrayname, arrayname.length, and arrayname.ubound
:getRemovableDrives <arrayname>
rem // unset array if exists
for /f "delims==" %%I in ('2^>NUL set %~1') do set "%%~I="
setlocal enabledelayedexpansion
set /a %~1.length = 0, %~1.ubound = -1
rem // note: nested for /f loops convert UCS-2 encoded WMI results to ANSI
for /f "skip=2 delims=" %%# in (
'wmic logicaldisk where "DriveType <> 3" get caption^,volumename /format:csv'
) do for /f "tokens=2,3 delims=," %%I in ("%%~#") do (
set "%~1[!%~1.length!].caption=%%~I"
set "%~1[!%~1.length!].volumename=%%~J"
set /a %~1.ubound = %~1.length, %~1.length += 1
)
rem // Trick to make private variables public
for /F "delims=" %%I in ('set %~1') do (
if defined %~1.ubound endlocal
set "%%~I"
)
exit /b
Hopefully you can use this to get you started. In case I guessed incorrectly about the drive type detection, see this page, Ctrl + F and find DriveType on the page.
This might get you started. It is in PowerShell. It gets a list of all removable (non-floppy) drives and presents a list for the user to chose from. If there is only one drive, it does not present the menu.
There is much to be done. There is no range or error checking on the user's input. And, of course, it is not stated what you want to do with the drive.
$drivelist = #(Get-WMIObject Win32_LogicalDisk -Filter "MediaType = 11")
if ($drivelist.Count -eq 0) { Write-Host 'There are no removable drives.'
} elseif ($drivelist.Count -eq 1) { $thedrive = $drivelist[0]
} else {
Write-Host 'Removable drives'
$i = 1
foreach ($drive in $drivelist) {
Write-Host $('{0}. {1} {2}' -f $i, $drive.DeviceId, $drive.VolumeName)
$i += 1
}
$dn = Read-Host -Prompt 'Enter the drive number.'
$thedrive = $drivelist[$dn - 1]
}
# At this point, $thedrive is a System.Management.ManagementObject#root\cimv2\Win32_LogicalDisk
# ready to be used for something.
$thedrive | Format-List * -Force
I have multiple text files that contains 3 lines of information that I want to output as one single line for each file
Example
File1.txt contains
User: "John"
Date: "13-March-2017"
Time: "10.30am"
Remarks: "xcvsfas"
File2.txt contains
User: "Mary"
Date: "13-March-2017"
Time: "11.30am"
Remarks: "xerteyas"
My expected output is as follows
c:\temp\file1.txt:User: "John"; Date: "13-March-2017"; Time: "10.30am"
c:\temp\file2.txt:User: "Mary"; Date: "13-March-2017"; Time: "11.30am"
I tried
findstr /s /i "user date time:" %inputfolder%\*.* > %outputfolder%\final.txt
EDIT: Code modified per new specifications posted in a comment in other answer... :(
#echo off
setlocal EnableDelayedExpansion
set "file="
(
for /F "tokens=1* delims=:" %%a in ('findstr /S /I "user date time" %inputfolder%\*.*') do (
if "!file!" neq "%%a" (
if defined file echo !file!:!out!
set "file=%%a"
set "out=%%b"
) else (
set "out=!out!; %%b"
)
)
echo !file!:!out!
) > %outputfolder%\final.txt
I'm assuming all your .txt are in the same folder and only them. Then I get the first three lines of each file and print them in one line by using the set command like:
#echo off
setlocal EnableDelayedExpansion
pushd <files dir>
for /f %%i in ('dir /b') do (
set "c=0"
for /f "tokens=*" %%j in ('type "%%i"') do (
set /a "c=c+1"
if "!c!" equ "3" (
set /p "=%%j" <nul
) else if "!c!" lss "3" (
set /p "=%%j; "<nul
)
)
echo(
)
popd
I tested with the input you gave and the result is:
User: "John"; Date: "13-March-2017"; Time: "10.30am";
User: "Mary"; Date: "13-March-2017"; Time: "11.30am";
Hope it helps.
You could loop through the files by a for loop and do the search individually -- like this:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_LOCATION=."
set "_INPUTFILES=File*.txt"
set "_OUTPUTFILE=%~dpn0.log"
rem // Write everything into output file:
> "%_OUTPUTFILE%" (
rem // Iterate over matching files recursively:
for /R "%_LOCATION%" %%F in ("%_INPUTFILES%") do (
rem // Initialise line string variable:
set "LINE=%%~F:"
rem // Search currently iterated input file for the keywords:
for /F "delims=" %%L in ('findstr /L /I /B "User: Date: Time:" "%%~F"') do (
rem // Store found item:
set "ITEM=%%L"
rem // Toggle delayed expansion in order not to lose exclamation marks:
setlocal EnableDelayedExpansion
rem // Build line string and transfer result over `endlocal` barrier:
for /F "delims=" %%E in ("!LINE!!ITEM!; ") do (
endlocal
set "LINE=%%E"
)
)
rem // Return built line string:
setlocal EnableDelayedExpansion
echo !LINE:~,-2!
endlocal
)
)
endlocal
exit /B
The fields User:, Date: and Time: are returned in the original order they appear in every file.
Please consider the following codes:
#echo off
setlocal enabledelayedexpansion
FOR /L %%G IN (0,1,19) DO (
set /a "Dday=%_day%+%%G"
if %mth% equ sml (
if !Dday! gtr 30 (
set "_day=1"
set /a "_month+=1"
)
if !_month! gtr 12 (
set "_month=1"
set /a "_year+=1"
)
) else (
if %mth% equ big (
if !Dday! gtr 31 (
set "_day=1"
set /a "_month+=1"
)
if !_month! gtr 12 (
set "_month=1"
set /a "_year+=1"
)
)
)
echo !Dday!/!_month!/!_year!.txt
)
Consider the following date: 20/04/2016
_day = 20; _month = 04; _year = 2016; mth=sml;
and my output is this:
It increases the day from 30 instead of changing it to 1. Can I know what have I done wrong? Please advise. Thanks
There are two problems in this script. First as #SomethignDark pointed out, you need to use !_day! instead of %_day%.
Second when Dday is greater than 30, %%G is 12. So you expression of !_day!+%%G will be 13 instead of 1.
So you need something like
...
FOR /L %%G IN (0,1,19) DO (
set /a "Dday=!_day!+%%G"
if !_day! equ 1 set /a "Dday=!_day!+%%G-12"
...
You know, pure batch is really cumbersome with date math. What will you do for months with 31 days? For February? During leap year? You should consider, if not altogether switching to another language with a proper date object, then at least borrowing from one. Here's a Batch + PowerShell hybrid example:
<# : batch portion
#echo off & setlocal
if "%~1"=="" (
echo usage: %~nx0 startdate
goto :EOF
)
set "startdate=%~1"
set "daysToAdd=19"
rem # evaluate PowerShell hybrid code and capture output as %%I
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
rem # do something useful with %%I here
echo %%I.txt
)
goto :EOF
: end batch / begin PowerShell hybrid code #>
# cast "startdate" environment variable value as a datetime object
[datetime]$d = $env:startdate
for ($i = 0; $i -le $env:daysToAdd; $i++) {
$d.addDays($i).toString("dd-MM-yyyy")
}
Or if you prefer the speed of VBScript, here's a Batch + VBScript hybrid example. Its allowed date input is perhaps not quite as flexible as that of PowerShell, but it does execute nearly instantly.
<!-- : batch portion
#echo off & setlocal
if "%~1"=="" (
echo usage: %~nx0 startdate
goto :EOF
)
set "startdate=%~1"
set "daysToAdd=19"
rem # evaluate VBScript hybrid code and capture output as %%I
for /f "delims=" %%I in ('cscript /nologo "%~f0?.wsf" "%startdate%" "%daysToAdd%"') do (
rem # do something useful with %%I here
echo %%I.txt
)
goto :EOF
: end batch / begin VBScript -->
<job>
<script language="VBScript">
if not IsDate(WSH.Arguments(0)) then
WSH.StdErr.WriteLine("Not a valid date.")
WSH.Quit(1)
end if
d = CDate(WSH.Arguments(0))
For i = 0 to WSH.Arguments(1)
d2 = DateAdd("d", i, d)
WSH.Echo(Day(d2) & "-" & Month(d2) & "-" & Year(d2))
Next
</script>
</job>
Or if you're more comfortable with JavaScript syntax, you could do a Batch + JScript hybrid solution.
#if (#CodeSection == #Batch) #then
#echo off & setlocal
if "%~1"=="" (
echo usage: %~nx0 startdate
goto :EOF
)
set "startdate=%~1"
set "daysToAdd=19"
rem // evaluate VBScript hybrid code and capture output as %%I
for /f "delims=" %%I in (
'cscript /nologo /e:JScript "%~f0" "%startdate%" "%daysToAdd%"'
) do (
rem // do something useful with %%I here
echo %%I.txt
)
goto :EOF
#end // end batch / begin JScript
Date.prototype.addDays = function(num) {
this.setDate(this.getDate() + num);
return this;
}
for (var i=0; i<WSH.Arguments(1); i++) {
var d = new Date(WSH.Arguments(0)).addDays(i);
WSH.Echo([d.getDate(), (d.getMonth() + 1), d.getFullYear()].join('-'));
}
Either way, VBScript, JScript, and PowerShell will all let you add n days to a date object, and that date object automatically handles calendar quirks without your explicitly needing to script for them.
I am looking at creating a batch file that extracts information out of a txt file from the last 3 months of log files, and out puts with the following information:
Computer name taken from file Path:
\\Server\e$\Users\\**COMPUTER_NAME**\path\search_file.txt
Search for total number of occurrences in a file (Nice to have - Not MUST)
Time of occurrence:
File being searched has a format of this when found:
09:24:08:17 (WS:PED:RunRequest)
Response: (0) None
Error : -2
So...
COMPUTER_NAME
Number of occurrences found
Time of occurrence i.e. 09:24:08:17
I have this as a start:
#echo off
echo.
echo Searching for all Error : -2...
setlocal enabledelayedexpansion
for %%a in (\\Sc0320svr0001\e$\Users\SC0320POS0003\E2ELOGS\ped_20140812_092355.dbg) do
(
set found=false
for /f "skip=2 tokens=*" %%b in ('find "Error : -2" "%%a"') do (
if "!found!"=="false" (
echo %%b >>output.txt
set found=true
)
)
)
With this I extract only the "Error : -2", and there could be MULTIPLE instances within.
Found the batch to do a count number:
#find /c /i "Error : -2" "\\Sc0320svr0001\e$\Users\SC0320POS0003\E2ELOGS\*.dbg" >>output.txt
However ONLY looking to output if greater than zero.
Portion of the file:
09:23:55:68 (WS:PED:OpenHandler)
Exit
09:23:55:76 (WS:PED:RunRequest)
Request: (1) Check PED status
09:23:55:86 (WS:PED:Write)
Data: 97
09:24:08:08 (WS:PED:Write)
Error: 30
09:24:08:17 (WS:PED:RunRequest)
Response: (0) None
Error : -2
Message :
Receipt :
This processes only one file...Check if it is doing the job:
#echo off
setlocal enableDelayedExpansion
set file_txt=apple.txt
set "current_line="
set "prev_line="
set "prev_prev_line="
set counter=0
for /f "tokens=* delims=" %%a in (%file_txt%) do (
rem echo -%%a-
if defined prev_line (
set prev_prev_line=!prev_line!
)
if defined current_line (
set prev_line=!current_line!
)
set "current_line=%%~a"
if "!current_line: =!" EQU "Error:-2" (
set /a counter=counter+1
echo(
echo Error -2 found
echo in %file_txt%
echo time is !prev_prev_line!
echo responces !prev_line!
echo(
)
)
echo total count %counter%
endlocal
EDIT. process multiple files
#echo off
setlocal enableDelayedExpansion
:: separate the file names with ;
set files_to_process=apple.txt;banana.txt;pear.txt
set "current_line="
set "prev_line="
set "prev_prev_line="
set counter=0
for %%f in (%files_to_process%) do (
for /f "tokens=* delims=" %%a in (%file_txt%) do (
rem echo -%%a-
if defined prev_line (
set prev_prev_line=!prev_line!
)
if defined current_line (
set prev_line=!current_line!
)
set "current_line=%%~a"
if "!current_line: =!" EQU "Error:-2" (
set /a counter=counter+1
echo(
echo Error -2 found
echo in %file_txt%
echo time is !prev_prev_line!
echo responces !prev_line!
echo(
)
)
)
echo total count %counter%
endlocal