Batch file to capture information from a website - batch-file

I want to get these informations from this website :
1. Day
2. Month
3. Year
4. Time
https://www.timeanddate.com/worldclock/fullscreen.html?n=37
how can i do this?
The best way would be to save all of them in different variables I would say and probably download the information with curl -o random.txt link
I already tried something like this :
curl -s -o r.txt link
set /p V=<r.txt
set V=%V:~4%
I'm sure there's a way easier and better way...

Try this:
#if (#x)==(#y) #end /***** jscript comment ******
#echo off
cscript //E:JScript //nologo "%~f0" "%~nx0" | findstr /r /e "[0123456789]"
exit /b %errorlevel%
***** end comment *********/
var strURL = "https://www.timeanddate.com/worldclock/fullscreen.html?n=37"
var ieOBJ = new ActiveXObject("InternetExplorer.Application");
ieOBJ.Visible = false
ieOBJ.Navigate2(strURL)
do {
WScript.Sleep(100);
} while (ieOBJ.Busy);
var innerText=ieOBJ.document.body.innerText;
WScript.Echo(innerText);
ieOBJ.Quit()
It should be a file with a .bat extension.

So you're basically asking how to extract specific information from a website. You'll need an HTML-parser like xidel for that:
xidel -s "https://www.timeanddate.com/worldclock/fullscreen.html?n=37"^
-e "tokenize(//div[#id='i_date'])[position() gt 1],//div[#id='i_time']"
28
January
2023
21:53:02
We grab the text-node from <div id=i_date>, convert it to a sequence by "tokenizing" on the white-space and only show item 2, 3 and 4. The text-node from <div id=i_time> we grab as-is.
To export these to a cmd-variable:
FOR /F "delims=" %A IN ('
xidel -s "https://www.timeanddate.com/worldclock/fullscreen.html?n=37"
-e "let $a:=tokenize(//div[#id='i_date']) return ($day:=$a[2],$month:=$a[3],$year:=$a[4]),$time:=//div[#id='i_time']"
--output-format^=cmd
') DO %A
ECHO %day% %month% %year% %time%
28 January 2023 21:53:02

Related

How to read different contents from a text file

I need to read the ID from a file like this:
BitLocker Drive Encryption: Configuration Tool version 10.0.16299
Copyright (C) 2013 Microsoft Corporation. All rights reserved.
Volume C: [OSDisk]
All Key Protectors
External Key:
ID: {31116007-D1FB-43CC-A89C-927487BD5F00}
External Key File Name:
31116007-D1FB-43CC-A89C-927487BD5F00.BEK
Numerical Password:
ID: {C7948F32-F2F0-4E55-AD2E-06E982DFDB4F}
Password:
xxxx-xxxxx-xxxxx-xxxxxx-xxxxx-xxxx-xxxxx-xxx
TPM:
ID: {6497FF93-F678-4317-B5D7-423E9D682BF0}
PCR Validation Profile:
0, 2, 4, 8, 9, 10, 11
and then run the following command to to export the keys to AD for all IDs
manage-bde -protectors -adbackup c: -id {C7948F32-F2F0-4E55-AD2E-06E982DFDB4F}
If you're not willing to utilise another built-in scripting language for this, and your file to read uses Windows standard line endings, I have an alternative idea.
Instead of directly searching for lines with ID: {…, you may be able to search for <Anything><Carriage Return><Line Feed><Space(s)><Password:>. You could further refine <Anything> should you feel the need, but in this case I do not think it's necessary:
#Echo Off
SetLocal DisableDelayedExpansion
Set "Src=input.txt"
Set "Str=Password:"
Set "ID="
(Set LF=^
% 0x0A %
)
For /F %%A In ('Copy /Z "%~f0" Nul')Do Set "CR=%%A"
SetLocal EnableDelayedExpansion
FindStr /RC:".*!CR!*!LF! *%Str%" "%Src%">"%TEMP%\_$.tmp"
EndLocal
For /F "UseBackTokens=2Delims={}" %%A In ("%TEMP%\_$.tmp")Do Set "ID={%%A}"
Del "%TEMP%\_$.tmp"
If Not Defined ID GoTo :EOF
manage-bde -protectors -adbackup c: -id %ID%
In the example above, I have used input.txt as the name of the text file you're reading, please modify that as needed.
FOR /f "tokens=2delims={}" %%a IN ('findstr /x /r /c:" *ID: {.*}" "%filename1%"') DO ECHO manage-bde -protectors -adbackup c: -id {%%a}
where filename1 contains the filename you are examining and the command is being echoed. Remove the echo keyword to execute manage-bde.
The findstr looks for lines that exactly match the pattern [spaces]ID: {string} and assigns the string between {} to %%a, then displays the required command line, reapplying the {}
a pure batch script, which takes advantage of the fact, you look for the key immediately after a "trigger line" (Numerical Password:)
#echo off
setlocal
set "flag="
for /f "tokens=*" %%a in (t.txt) do (
if defined flag (for %%b in (%%a) do set "key=%%b") & goto :found
if "%%a" == "Numerical Password:" set "flag=yes"
)
echo not found & goto :eof
:found
echo %key%
Perhaps use a windows script to handle the task? This can be executed directly, using wscript, or from a batch file using cscript:
cscript //nologo myscript.js
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile("C:\\myfile.txt", 1);
var content = file.readAll();
// Do something with file content
file.close();
You might be able to get what want with Regular Expressions and FindStr. Partial solution since I'm lazier than you. ;)
c:\projects>findstr {[0-9A-F/-]*} data.txt
ID: {31116007-D1FB-43CC-A89C-927487BD5F00}
ID: {C7948F32-F2F0-4E55-AD2E-06E982DFDB4F}
ID: {6497FF93-F678-4317-B5D7-423E9D682BF0}
EDIT: I overlooked that all IDs and created a solution based on the example line
The following PowerShell one liner will extract the ID from a text file .\BitLocker.txt
PoSh> Select-String -Path .\BitLocker.txt -Pattern 'Numerical Password' -Context 0,1|ForEach-Object {($_.Context.Postcontext.Trim() -split ' ')[1]}
{C7948F32-F2F0-4E55-AD2E-06E982DFDB4F}
To be on topic wrapped in a batch:
#Echo off
For /f "usebackq delims=" %%A in (`
powershell -NoP -C "Select-String -Path .\BitLocker.txt -Pattern 'Numerical Password' -Context 0,1|% {($_.Context.Postcontext.Trim() -split ' ')[1]}"
`) Do Set "ID=%%A"
manage-bde -protectors -adbackup c: -id %ID%

using output from mediainfo as variable in another command

So I'm trying to setup an easy way of starting videos with a bat file, and having that run Mediainfo first to get the length of the video so it can then stop vlc or whatever else when it's done playing.
Complete name : C:\Users\Tyler\Desktop\Psych s05e11.mp4
Format : MPEG-4
Format profile : Base Media
Codec ID : isom (isom/iso2/avc1/mp41)
File size : 116 MiB
Duration : 42 min 36 s
Overall bit rate : 382 kb/s
Writing application : Lavf55.13.102
That's the output from mediainfo I got in a txt file, I'm trying to just pull the 42 and the 36 from the duration bit and use it in another command. I should also add that these numbers have to be used separately. Thanks!
Edit: Thanks for replying everyone love the help;
Here's what I'm trying to run now:
mediainfo.lnk --Language=raw --Output=General;%Duration% "C:\Users\Tyler\Desktop\Psych s05e11.mp4"
and the output is:
2556249
Now I need a way to take the first four digits and use them in a another command, somehow make 2556 a variable?
If you need the duration, use e.g. this command:
mediainfo "--Output=General;%Duration%" YourFileName.ext
In a general way, when you think to some automation, prefer to use e.g.:
mediainfo -f --Language=raw YourFileName.ext
and select the lines which better fits your need, avoid fields with "/String" because they are intended only for display (not for automation).
Jérôme, developer of MediaInfo.
Okay here's what I did finally, thanks for all the help!
C:\mediainfo\MediaInfo.exe --Language=raw --Output=General;%%Duration%% "C:\Users\Tyler\Desktop\Psych_s05e11.mp4" >out.txt
set /p $Duration= <out.txt
set $Duration=%$Duration:~0,4%
echo Result = %$Duration%
del out.txt
pause
and the output is:
C:\mediainfo\MediaInfo.exe --Language=raw --Output=General;%Duration% "C:\Users\Tyler\Desktop\Psych_s05e11.mp4" >out.txt
set /p $Duration= <out.txt
set $Duration=2556
echo Result = 2556
Result = 2556
del out.txt
pause
Press any key to continue . . .
took #echo off outta there so you could see it all
Using FOR /F
#echo off
for /f "delims=" %%a in ('mediainfo "--Output=General;%%Duration%%" "C:\Users\Tyler\Desktop\Psych\s05e11.mp4"') do set $Duration=%%a
Echo %$Duration%
Using a temporary file
#echo off
mediainfo.exe --Language=raw --Output=General;%%Duration%% "C:\Users\Tyler\Desktop\Psych s05e11.mp4" >out.txt
set /p $Duration= <out.txt
set $Duration=%$Duration:~0,4%
echo Result = %$Duration%
del out.txt
Another way using #Jérôme Martinez [raw -output] idea.
Without temporary file, using findstr :
#echo off
for /f "tokens=2 delims=:" %%a in ('mediainfo -f --Language=raw "C:\Users\Tyler\Desktop\Psych s05e11.mp4" ^| findstr /i "duration"') do (
set $Duration=%%a
goto:next
)
:next
set $Duration=%$Duration:~1,4%
echo %$Duration%

I want to run more than 1 command with the FOR /F

I'm trying to make a script to:
send a request to an url, then append (>>) the %%a variable i set in the FOR /F command IF i get a certain response from the command i run with FOR /F.
I tried with 2 scripts that are the followings:
FOR /F %%a in (usernames.txt) do (
IF "curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username" EQU "{"valid":true,"suggestions":[],"inuse":false}" %%a >> usernames1.txt
and
set /p VAR = < tmpFile
FOR /F %%a in (usernames.txt) do (
curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username
> tmpFile
IF VAR={"valid":true,"suggestions":[],"inuse":false}
%%a >> usernames1.txt)
EDIT: good enough with that script, thanks guys. but i've got another thing: can i add more than 1 variable to the script? I mean a variable like %%a, that takes every line from another txt file
First, you set VAR once, whereas your temporary file does not exist. Then you test with = instead of == and without the ! chars.
And don't put too many spaces like if you were using a real shell like bash :)
As Magoo noted, I also had to fix set /p VAR = < tmpFile to remove the extra spaces. Batch has a tendency to take them literaly.
(another example: echo foo > file: file now contains "foo ".
(needless to say that without enabledelayedexpansion it wouldn't work either because lots of things happen inside the FOR loop)
The fixed code (also had to protect the test string with extra quotes or it wouldn't work):
setlocal enabledelayedexpansion
del usernames1.txt >NUL 2>NUL
FOR /F %%a in (usernames.txt) do (
curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username > tmpFile 2>NUL
set /p VAR=<tmpFile
IF "!VAR!"=="{"valid":true,"suggestions":[],"inuse":false}" echo %%a >> usernames1.txt
)
I tested it with a random list of user names and changing "valid":true by "valid":false and the names were issued.

Using a .bat to extract text between two words

I have a media server and I'm attempting to automate ripping my collection of movies and any future movies using MakeMKV. Ripping and moving is working without a hitch. The problem I'm running into is occasionally MakeMKV doesn't assign a title to the MKVs and I end up with title00.mkv which Media Center Master obviously cannot even begin to try to match to any metadata.
MakeMKV does offer the ability to get the information from the disc which I have print to info.txt which looks like this.
MSG:1005,0,1,"MakeMKV v1.8.10 win(x64-release) started","%1 started","MakeMKV v1.8.10 win(x64-release)"
DRV:0,2,999,1,"HD-DVD-ROM HL-DT-ST BD-RE GGW-H20L YL05","FARFROMHOME_16X9","\\Device\\CdRom0"
DRV:1,256,999,0,"","",""
DRV:2,256,999,0,"","",""
DRV:3,256,999,0,"","",""
DRV:4,256,999,0,"","",""
DRV:5,256,999,0,"","",""
DRV:6,256,999,0,"","",""
DRV:7,256,999,0,"","",""
DRV:8,256,999,0,"","",""
DRV:9,256,999,0,"","",""
DRV:10,256,999,0,"","",""
DRV:11,256,999,0,"","",""
DRV:12,256,999,0,"","",""
DRV:13,256,999,0,"","",""
DRV:14,256,999,0,"","",""
DRV:15,256,999,0,"","",""
FARFROMHOME_16X9 is the label for the disc.
How can I extract this and rename my .mkv when makemkv has finished?
Here is my BAT so far (my first attempt at a .bat):
makemkvcon64 -r info disc > info.txt
makemkvcon64 --minlength=3600 mkv disc:0 all C:\Users\HTPC\MakeMKV_Temp\
START /WAIT makemkvcon64.exe
cd "c:\Program Files (x86)\FreeEject\"
FreeEject d:
move C:\Users\HTPC\MakeMKV_Temp\*.mkv C:\Users\HTPC\Movies\
Renaming the file before the move would be ideal.
Although you posted an ample description of your problem and data, you have not explained what exactly you want as result, so I must guess a couple points. The lines below extract the sixth comma-separated token from the second line of info.txt file:
for /F "skip=1 tokens=6 delims=," %%a in (info.txt) do set "discLabel=%%~a" & goto continue
:continue
echo The label of the disk is: %discLabel%
This is the output of previous lines when they are executed on your example data:
The label of the disk is: FARFROMHOME_16X9
You also have not indicated the name of the file you want to rename (before move it). Below is a possible solution to your problem that should be adjusted when previous unclear points be defined:
makemkvcon64 -r info disc > info.txt
for /F "skip=1 tokens=6 delims=," %%a in (info.txt) do set "discLabel=%%~a" & goto continue
:continue
makemkvcon64 --minlength=3600 mkv disc:0 all C:\Users\HTPC1\MakeMKV_Temp\
START /WAIT makemkvcon64.exe
cd "c:\Program Files (x86)\FreeEject\"
FreeEject d:
ren C:\Users\HTPC1\MakeMKV_Temp\TheNameHere.mkv %discLabel%.mkv
move C:\Users\HTPC1\MakeMKV_Temp\*.mkv C:\Users\HTPC1\Movies\
I've been wrangling with the same thing and created something that works fairly well.
MakeMKV uses it's own output FileName like you indicated "title00.mkv" or something similar.
I've created two(2) batch files to perform my home movie automation.
The first is "RipWorkflow_DVD.bat", which handles all the heavy lifting to call MakeMKV first to rip the content to my drive. Also in this file is a call to Handbrake to convert the MKV to MP4 (my stupid "smart" tv won't play MKV, but likes MP4)
The second batch file "OneStepDVDRip.bat" calls the first, but with parameters I choose for
a) location of the MKV
b) the output name of my MP4
c) the minLength of a track to locate and rip to MKV
Here is the code for "OneStepDVDRip.bat"
call "C:\Users\Todd\Desktop\RipWorkflow_DVD.bat" "Z:\Video\TrueStory" "E:\My Videos\Movies\Drama\True Story (2015).mp4" 3600
Here is the code for "RipWorkflow_DVD.bat"
#echo off
cls
setlocal ENABLEDELAYEDEXPANSION
SET input=%1
SET output=%2
SET minlength=%3
echo
echo %input%
echo %output%
echo
if not exist %input% ( mkdir "%input%" )
call "C:\Program Files (x86)\MakeMKV\makemkvcon64.exe" --minlength=%minlength% --decrypt mkv disc:0 0 "%input%
timeout /t 5 /nobreak
for %%F in (%input%\*.mkv) do (
echo %%~dpnxF
echo %output%
call "C:\Program Files\Handbrake\HandbrakeCLI.exe" -v1 -i %%~dpnxF --main-feature -o %output% -f mp4 --markers -e x264 -b 2000 -a 1 -E faac -6 dpl2 -R 44.1 -B 128 -D 1.75 --subtitle-forced -x ref=2:bframes=2:subme=6:mixed-refs=0:weightb=0:8x8dct=0:trellis=0
timeout /t 5 /nobreak
DEL %%F /Q
)
endlocal

batch - File last modification time with seconds

I want to know when a file has been modified for the last time.
I can get these infos using the following batch script:
FOR %%i IN (myfile) DO SET modif_time=%%~ti
The problem is that I need the second of the last modification and the command %~t returns the date and the time with only hours and minutes.
I can only check the seconds by manually viewing the "property window" file by file.
How can I get the time with seconds in batch?
In Windows 7 and forward (or via Resource Kit for XP) you can use forfiles for this. Something like:
forfiles /m *.* /c "cmd /c ECHO The last modified date of: #file is: #ftime"
In a directory with the following files:
myTest.txt
myTest2.txt
I get:
The last modified date of: "myTest.txt" is: 13:21:07
The last modified date of: "myTest2.txt" is: 13:21:20
wmic datafile where name="FileName" get LastModified
FileName must contain the full path with double backspaces.
Sorting example (recent first):
for /f "delims=" %a in ('wmic datafile where "drive='c:' and path='\\windows\\'" get LastModified^,Name /format:table^|find ":"^|sort /r') do #echo %a
wmic datafile where "drive='c:' and path='\\windows\\'" get "Last Modified",Name
You can embed a small JScript in the batch file to get the last modified epoch:
#if (#a==#b) #end /*
#echo off
SetLocal EnableDelayedExpansion
set EPOCH=0
FOR /F "delims=" %%D in ('cscript /nologo /e:jscript "%~f0" "%1"') do (
set EPOCH=%%D
)
echo Last modified (epoch-seconds): !EPOCH!
goto :eof
*/
var fs = new ActiveXObject("Scripting.FileSystemObject");
var filename = WSH.Arguments(0)
var millis = -1
if (fs.FileExists(filename))
{
var file = fs.GetFile(filename);
millis = Date.parse(file.DateLastModified) / 1000;
}
WSH.Echo(millis);
The /* */ will comment out the batch script while running as a JScript, and the #if (#a==#b) #end and goto :eof will skip the JScript while running as a batch script
>epoch.bat epoch.bat
Last modified (epoch-seconds): 1533282229
>epoch.bat "epoch.bat"
Last modified (epoch-seconds): 1533282229
>epoch.bat notareal.file
Last modified (epoch-seconds): -1

Resources