batch download images from url with for - batch-file

I need to download 300 images from site.com/folder/ using the following format: 1.png, 2.png ... 300.png
Is there a way to do this inside a batch file or using the command prompt?

Wth curl like this:
curl -o "#1.png" http://example.com/folder/[1-300].png

Here is an example to download some batch codes from a file that can be created by this script if not exist, and of course you can add or modify what you want of urls in this file !
You can add your urls in the text file named Urls.txt
Firstly, the script check for the text file named Urls.txt if exist in same location where this batch is executed and read from it the urls line by line to download them !
So, if you want to change those urls to yours, just change it from the text file Urls.txt not from the batch, i mean you can create a text file and name it to Urls.txt and put what you want as urls on this file line by line of course and let the script do its job
#echo off
Mode 110,3 & color 0A
Title Download file from web using powershell and batch by Hackoo 2017
Set "List_Urls_File=Urls.txt"
If not exist "%List_Urls_File%" Call :Create_Urls_File
Setlocal enabledelayedexpansion
#For /f "delims=" %%a in ('Type "%List_Urls_File%"') do (
Set "URL=%%a"
Rem we set the Filename from the variable !url!
#for %%# in (!url!) do ( set "File=%%~xn#" )
Rem Check if the file name contains a dot "."
Rem If not we increment the counter +1 for file to be download
ECHO !File! | FIND /I ".">Nul 2>&1
If "!errorlevel!" NEQ "0" (
Set /a Count+=1
cls & echo(
echo Downloading file "File-!Count!.bat" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading File-!Count!.bat"' "'Please wait... Downloading File-!Count!.bat....'" 'info' 4
Call :Download "%%a" "File-!Count!.bat"
) else (
cls & echo(
echo Downloading file "!File!" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading !File!"' "'Please wait... Downloading !File!....'" 'info' 4
Call :Download "%%a" "!File!"
)
)
Explorer "%~dp0" & exit
::*********************************************************************************
:Download <url> <File>
Powershell.exe -command "(New-Object System.Net.WebClient).DownloadFile('%1','%2')"
exit /b
::*********************************************************************************
:Create_Urls_File
(
echo https://pastebin.com/raw/XvyhRzT6
echo https://pastebin.com/raw/QqnZ0MjQ
echo https://pastebin.com/raw/tHsKw15V
echo https://pastebin.com/raw/VCnTbLB6
echo https://pastebin.com/raw/3zUTrWUz
echo https://pastebin.com/raw/31auQeFz
echo https://pastebin.com/raw/xF0uXThH
echo https://pastebin.com/raw/uzsGQD1h
echo https://pastebin.com/raw/3TmVYiZJ
echo https://pastebin.com/raw/Ntc8SZLU
echo https://pastebin.com/raw/jnpRBhwn
echo https://www.virustotal.com/static/bin/vtuploader2.2.exe
echo http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe
)>"%List_Urls_File%"
exit /b
::*********************************************************************************
:BalloonTip $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*************************************************************************

Numbered-Files Downloader 1.0
Here is a complete batch script that is doing exactly what you asked for. You don't need to download any executable files, this is 100% batch script and it should works on any (recent) Windows installation.
All you need to do is to edit the _URL variable (Line 11) and replace "example.com/folder..." with the actual URL of the files you want to download. After that, you can run the script and get your files.
Note that in your URL, this string: _NUMBERS_ is a keyword-filter that will be replaced by the incremented numbers in the final download function.
All your downloaded files will be saved in the directory where this script is located. You can choose an other directory by uncommenting the _SAVE_PATH variable (Line 15).
Finally the following variables can be changed to configure the series of numbers:
_START : The file numbers starts with this value.
_STEP   : Step between each files.
_END    : The file numbers ends with this value.
Leading Zeros
Currently, the counter doesn't support leading zeros.
EX. From Picture_001.jpg to Picture_999.jpg
But otherwise it should work fine for something like this:
EX. From Picture_1.jpg to Picture_999.jpg
I will try to find some time to add this option, it shouldn't be too difficult.
Feel free to modify & enhance this script if you need!
Numbered-DL.cmd
#echo off
setlocal EnableDelayedExpansion
rem STACKOVERFLOW - QUESTION FROM:
rem https://stackoverflow.com/questions/45796990/batch-download-images-from-url-with-for
:VARIABLES
rem WHERE YOU WANT TO SAVE FILES
rem "%~dp0" is a variable for the same folder as this script, so files should be saved in the same folder.
rem If you want to save the downloaded files somewhere else, uncomment the next line and edit the path.
SET "_SAVE_DIR=%~dp0"
rem SET _SAVE_PATH=C:\Folder\
rem DOWNLOAD THIS FILE URL
rem
rem "_NUMBERS_" WILL BE REPLACED BY THE COUNTER
rem CURRENLY IT DOESN'T SUPPORT CHOOSING A NUMBERS OF ZEROS FOR THE COUNTER EX: 001,002,003...
rem BUT IT SHOULDN'T BE TOO HARD TO IMPLEMENT, MAYBE ILL ADD THIS IN THE FUTURE.
rem
rem SET _FILE_URL=https://example.com/folder/_NUMBERS_.png
SET "_FILE_URL=https://cweb.canon.jp/eos/lineup/r5/image/downloads/sample0_NUMBERS_.jpg"
rem FOR THIS EXAMPLE THE SCRIPT WILL DOWNLOAD FILES FROM "sample01.jpg" TO "sample05.jpg"
SET _START=1
SET _STEP=1
SET _END=5
:CMD_PARAMS
IF NOT [%1]==[] SET "_FILE_URL=%1"
IF NOT [%2]==[] SET "_SAVE_DIR=%2"
:PATH_FIX
rem REMOVE THE LAST CHAR IF IT IS "\"
IF [%_SAVE_DIR:~-1%] == [\] SET "_SAVE_DIR=%_SAVE_DIR:~0,-1%"
:DETAILS_DISPLAY
ECHO.
ECHO SCRIPT: Numbered-Files Downloader 1.0
ECHO AUTHOR: Frank Einstein
ECHO.
ECHO.
ECHO INPUTS
ECHO _URL: %_FILE_URL%
ECHO _SAVE_DIR: %_SAVE_DIR%
ECHO.
ECHO _START: %_START%
ECHO _STEP= %_STEP%
ECHO _END= %_END%
ECHO.
ECHO.
CALL :DOWNLOAD_LOOP
ECHO.
ECHO EXECUTION COMPLETED
ECHO.
PAUSE
EXIT /B
:DOWNLOAD_LOOP
SET FINAL_URL=%_FILE_URL%
FOR /L %%G IN (%_START%,%_STEP%,%_END%) DO (
rem REPLACE URL'S KEYWORD WITH NUMBERS
SET NUM=%%G
SET FINAL_URL=%FINAL_URL:_NUMBERS_=!NUM!%
rem CUMSTOM BATCH FUNCTION FOR DOWNLOADING FILES
rem
rem SYNTAX:
rem echo CALL :DOWNLOAD !FINAL_URL!
CALL :DOWNLOAD !FINAL_URL! !_SAVE_DIR!
)
Goto :EOF
rem PAUSE
rem EXIT /B
rem FUNCTIONS
:DOWNLOAD
setlocal
SET "DL_FILE_URL=%1"
SET "DL_SAVE_DIR=%2"
rem EXTRACT THE FILENAME FROM URL (NEED TO FIX THIS PART?)
FOR %%F IN ("%DL_FILE_URL%") DO SET DL_FILE_NAME=%%~nxF
IF "%DL_SAVE_DIR:~-1%" == "\" SET "DL_SAVE_DIR=%DL_SAVE_DIR:~0,-1%"
IF NOT [%2]==[] SET "DL_SAVE_FILE=%DL_SAVE_DIR%\%DL_FILE_NAME%"
IF [%2]==[] SET "DL_SAVE_FILE=%~dp0%DL_FILE_NAME%"
rem :BITSADMIN
ECHO.
ECHO DOWNLOADING: "%DL_FILE_URL%"
ECHO SAVING TO: "%DL_SAVE_FILE%"
ECHO.
bitsadmin /transfer mydownloadjob /download /priority foreground "%DL_FILE_URL%" "%DL_SAVE_FILE%"
rem BITSADMIN DOWNLOAD EXAMPLE
rem bitsadmin /transfer mydownloadjob /download /priority foreground http://example.com/filename.zip C:\Users\username\Downloads\filename.zip
endlocal
GOTO :EOF

try with winhttpjs.bat:
set "baseLink=http://example.org/folder/"
for /l %%a in (1;1;300) do (
winhttpjs.bat "%baseLink%%%a.png" -saveto %%a.png
)

Related

Batch script: Convert path to linux format using wslpath

I was trying to convert current working directory of a .bat script into linux format by using wsl wslpath. To show you it works on CMD:
However, when I put it in a .bat file, and changed %cd% to %~dp0, the path is empty:
test.bat contains:
FOR /F %%i IN ('wsl wslpath -a %~dp0') DO set lp=%%i
echo %lp%
Any idea why?
Try this:
echo "%cd%" -- "%~dp0"
%cd% returns the path without ending backslash. So you can add a second variable that clears it.
set "scriptDir=%~dp0"
set "scriptDir=%scriptDir:~0,-1%"
UPDATE (with string substitution only - use the toLinuxPath subroutine)
#echo off
call ::toLinuxPath "%userprofile%\AppData\Local\Temp" tempF
echo %tempF%
exit /b 0
:toLinuxPath [returnVariable - the result will be stored in it; If omitted will be only echoed]
setlocal
set "_path=%~p1"
set "name=%~nx1"
set "drive=%~d1"
set "rtrn=%~2"
set "result=/mnt/%drive:~0,1%%_path:\=/%%name%"
endlocal & (
if "%~2" neq "" (
set "%rtrn%=%result%"
) else (
echo %result%
)
)

Conditional concatenation in batch

I am trying to append an underscore to strings when they are not blank. This is for a backup program, where the name of the folder is [prefix]_[date]_[time]_[suffix], except the first and last underscores are supposed to only be added when the [prefix] or [suffix] are not empty.
I've attempted to concatenate with set PRX=%PRX% and _ as I read on some forum, although the and wasn't recognized (it just outputted "backup and _"). I also tried jumping around the files with "goto", but to no avail. I think it's with the concatenation.
#echo off
set /p DRV=Enter drive/directory to back up (e.g. %userprofile% or C:):
set /p DRU=Enter directory to save to (e.g. C:\backup or F:):
set /p PRX=Enter the prefix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]:
set /p SFX=Enter the suffix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]:
if %PRX% NEQ "" (set PRX=%PRX%_)
if %SFX% NEQ "" (set SFX=_%SFX%)
set /p CONT=%CD%, Are you sure you want to continue (Y/N)?
if /i "%CONT%" EQU "N" goto :cancel
cls
echo Initialising...
%DRV:~0,1%:
cd\
set DAT=%date:~6,4%-%date:~3,2%-%date:~0,2%
set TIM=%time:~0,2%-%time:~3,2%-%time:~6,2%
mkdir "%DRU%\%PRX%%DAT%_%TIM%%SFX%"
echo Cloning Files...
echo.
xcopy "%DRV%\*" "%DRU%\%PRX%%DAT%_%TIM%%SFX%" /s
I inputted
Enter drive/directory to back up (e.g. %userprofile% or C:): %userprofile%\downloads
Enter directory to save to (e.g. C:\backup or F:): %userprofile%\backup
Enter the prefix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]: (that is empty)
Enter the suffix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]: aa
the outputted folder was named "_2019-09-10_17-08-35_aa" as opposed to "2019-09-10_17-08-35_aa", not what I was expecting.
I appreciate any reply, thank you for your time.
String comparison is very explicit.
IF "%PRX%" NEQ "" (SET "PRX=%PRX%_")
IF "%SFX%" NEQ "" (SET "SFX=_%SFX%")
It is easy to get correctly formatted data and time values regardless of region settings.
FOR /F %%A IN ('powershell -NoLogo -NoProfile -Command "Get-Date -Format 'yyyy-MM-dd'"') DO (
SET "DAT=%%A"
)
FOR /F %%A IN ('powershell -NoLogo -NoProfile -Command "Get-Date -Format 'HH-mm-ss'"') DO (
SET "TIM=%%A"
)

Concatenate text in batch

I have sql files in a folder structure like the following :
C:\Users\Peter\Desktop\SQL_FILES\data_structure\customer1\test.sql
C:\Users\Peter\Desktop\SQL_FILES\data_structure\customer2\test.sql
C:\Users\Peter\Desktop\SQL_FILES\data_structure\customer3\test.sql
C:\Users\Peter\Desktop\SQL_FILES\data_structure\customer4\test.sql
........
I want to make a script which reads the path (C:\Users\Peter\Desktop\SQL_FILES),
the name of the file(test.sql) and a text
and then concatenate the text in the end of each test.sql file.
Could you help me please ?
Thanks in advance
:: Hide Command and Set Scope
#echo off
setlocal EnableExtensions
mode 140,50
set /p AbsolutePath="Enter the path of root folder :"
echo.
set /p FileName="Enter the filename with it's extension (ie. test.sql):"
echo.
echo Enter your inserts
echo Press Enter twice when finished
echo (text may not contain ^<, ^>, ^|, ^&, or un-closed quotes)
ver > NUL
set new_line=""
:still_typing
set /p new_line=">"
if errorlevel 1 echo. >> temp.txt & set /p new_line=">"
if errorlevel 1 echo Sending message. . . & goto done_typing
echo %new_line% >> temp.txt
goto still_typing
:done_typing
echo done
:End
endlocal
pause >nul
=====================================
For example :
The file test.sql for example contains initially :
INSERT INTO TEST(COL1,COL2,COL3) VALUES(3,4,5);
And after the execution of batch supposing I add an empty line and two inserts in the text :
INSERT INTO TEST(COL1,COL2,COL3) VALUES(3,4,5);
INSERT INTO TEST(COL1,COL2,COL3) VALUES (1,2,3);
INSERT INTO TEST(COL1,COL2,COL3) VALUES (2,3,4);
The Batch file below use a different method to do the same, but in a simpler way. This code may be modified in any point you wish; for example, if you want not that the filename must include a wild-card.
#echo off
setlocal
set /p "AbsolutePath=Enter the path of root folder: "
echo/
set /p "FileName=Enter the filename with a wild-card (ie. test*.sql): "
echo/
echo Enter your inserts
echo Press Ctrl-Z and Enter when finished
copy CON temp.txt > NUL
echo/
echo Typing done
echo/
for /R "%AbsolutePath%" %%a in (%FileName%) do type temp.txt >> "%%a"

uTorrent Batch Script

I wrote myself a script based off another one that I found and I'm having trouble figuring out why it's not working.
How it is supposed to work is once a torrent has finished downloading, it runs the script and grabs the Label on the torrent. For testing, I was downloading a song with the label of Music.
When it gets to the point at :copyfile, it won't move it into the correct directory. Instead of moving into F:\Completed Torrents\Music, it just moves into F:\Completed Torrents.
Can someone please point out what I'm missing because I've looked through it thrice already and it's driving me crazy. The script is below.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set fromdir=%1
set name=%2
set label=%3
set kind=%4
set filename=%5
set savepartition="F:\Completed Torrents"
set winrar="C:\Program Files (x86)\WinRAR\WinRAR.exe"
set torrentlog="F:\Torrent Scripts\logs\torrentlog.txt"
set handledlog="F:\Torrent Scripts\logs\handled_torrents.txt"
set errorlog="F:\Torrent Scripts\logs\ErrorLog.txt"
set label_prefix=""
echo Input: %fromdir% %name% %label% %kind% %filename%
rem Check if the label has a sub label by searching for \
if x%label:\=%==x%label% goto skipsublabel
rem Has a sub label so split into prefix and suffix so we can process properly later
echo sub label
for /f "tokens=1,2 delims=\ " %%a in ("%label%") do set label_prefix=%%a&set label_suffix=%%b
rem add the removed quote mark
set label_prefix=%label_prefix%"
set label_suffix="%label_suffix%
echo.prefix : %label_prefix%
echo.suffix : %label_suffix%
goto:startprocess
:skipsublabel
echo Skipped Sub Label
goto:startprocess
:startprocess
echo %date% at %time%: Handling %label% torrent %name% >> %handledlog%
rem Process the label
if %label%=="Movies" goto known
if %label%=="Music" goto known
if %label_prefix%=="TV" goto TV
rem Last resort
rem Double underscores so the folders are easier to spot (listed on top in explorer)
echo Last Resort
set todir=%savepartition%\Unsorted\__%name%
if %kind%=="single" goto copyfile
if %kind%=="multi" goto copyall
GOTO:EOF
:known
echo **Known Download Type - %label%
set todir=%savepartition%\%label%\%name%
echo todir = %todir%
GOTO:process
:TV
echo **Known Download Type - %label%
set todir=%savepartition%\%label_prefix%\%label_suffix%
echo todir = %todir%
GOTO:process
:process
rem If there are rar files in the folder, extract them.
rem If there are mkvs, copy them. Check for rars first in case there is a sample.mkv, then we want the rars
if %kind%=="single" goto copyfile
if exist %fromdir%\*.rar goto extractrar
if exist %fromdir%\*.mkv goto copymkvs
if %kind%=="multi" goto copyall
echo Guess we didnt find anything
GOTO:EOF
:copyall
echo **Type unidentified so copying all
echo Copy all contents of %fromdir% to %todir%
xcopy %fromdir%\*.* %todir% /S /I /Y
GOTO:EOF
:copyfile
rem Copies single file from fromdir to todir
echo Single file so just copying
echo Copy %filename% from %fromdir% to %todir%
xcopy %fromdir%\%filename% %todir%\ /S /Y
GOTO:EOF
:copymkvs
echo Copy all mkvs from %fromdir% and subdirs to %todir%
xcopy %fromdir%\*.mkv %todir% /S /I /Y
GOTO:EOF
:extractrar
echo Extracts all rars in %fromdir% to %todir%.
rem Requires WinRar installed to c:\Program files
if not exist %todir% mkdir %todir%
IF EXIST %fromdir%\subs xcopy %fromdir%\subs %todir% /S /I /Y
IF EXIST %fromdir%\subtitles xcopy %fromdir%\subtitles %todir% /S /I /Y
call %winrar% x %fromdir%\*.rar *.* %todir% -IBCK -ilog"%todir%\RarErrors.log"
IF EXIST %fromdir%\*.nfo xcopy %fromdir%\*.nfo %todir% /S /I /Y
GOTO:EOF
EDIT
Also, for some reason, on line 39 nothing prints to the log. For those who wish to see the code with line numbers: http://hastebin.com/juqokefoxa.dos
A couple of bits for ya:
1) Likely, your script isn't moving the files. Preferences / Directories has an option to move downloads when completed. verify that these settings aren't doing the file moving.
2) uTorrent locks the files on completion so that seeding can continue. To change this behavior, go to Preferences / Advanced and set bt.read_only_on_complete to false
3) you will still be foiled because "Run this program when a torrent finishes" doesn't really do what it says. It runs the program as downloading reaches 100%, but while uTorrent is still either moving the file or seeding. See my bug report here.
A quick summary of the post, just in case that post gets deleted: you have to set the command in "Run this program when a torrent changes state:", add a %S parameter and check that %S == 11
4) Just a tip from my attempt at doing something very similar: when you set the variables from the arguments, add a tilde (%~1 instead of %1). This will strip the quotes off and let us more easily build command lines with the variables later.
You say that the log is not being written to. Try this as a test and see if it writes to the log.
If it doesn't there there is some other fundamental problem.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set "fromdir=%~1"
set "name=%~2"
set "label=%~3"
set "kind=%~4"
set "filename=%~5"
set "savepartition=F:\Completed Torrents"
set "winrar=C:\Program Files (x86)\WinRAR\WinRAR.exe"
set "torrentlog=F:\Torrent Scripts\logs\torrentlog.txt"
set "handledlog=F:\Torrent Scripts\logs\handled_torrents.txt"
set "errorlog=F:\Torrent Scripts\logs\ErrorLog.txt"
set "label_prefix="
set "handledlog=%userprofile%\desktop\handled_torrents.txt"
>> "%handledlog%" echo Input: "%fromdir%" "%name%" "%label%" "%kind%" "%filename%"
>> "%handledlog%" echo %date% at %time%: Handling "%label%" torrent "%name%"

Touch file to update the date/time of file? (Modified Date) (WindowsXP BatchScript)

What's a batch script command to touch on a file to update its date and time to the current date and time? (Modified Date)
For example, Joe Blow sends me a text document which he created months ago, when he emails me the document, I want to keep track of how old it is from the day I received it (not when he created it) so I want to update the file's date/time to the current date/time.
I have a batch script to automatically weed out files that haven't been edited within 90 days, so this is troublesome when I receive a particularly older file then all of a sudden it disappears.
And I need it via a batch script as I have hundreds of files to manage, and it's for archiving files.
I can't take all the credit, but I did look through my todo.txt to find it
Microsoft "touch" it's a KB article from like 5 years ago
The jist of it is you use copy /b MYFILENAME +,, where MYFILENAME is your file
This is an expansion on aflat's anwer.
1) Microsoft support provides an explanation and simple touch.bat script.
2) My custom touch.cmd, which expands on the MS script by including "touch /?" help text.
3) My custom midastouch.cmd, which provides several options including recursive operation and date operations.
As aflat wrote, the simple answer is:
copy /b FILENAME +,,
As you might expect, FILENAME can include relative or absolute path and wildcards like *.txt.
1. Microsoft1 support:
The following MS-DOS command updates the date and time stamps of a
file named "EXAMPLE" without altering the contents of the file. This
is similar to the TOUCH utility found in XENIX and in some third-party
MS-DOS toolkits.
COPY /B EXAMPLE +,,
The COPY command can concatenate a file onto an existing file when
used in the form:
COPY FILE1+FILE2
In this example, the contents of FILE2 are appended to FILE1, leaving FILE2 unchanged. When copying in this mode, the COPY command
switches to ASCII mode where the ^Z (0x01A) end-of-file marker is
honored.
Therefore, with the above command, the /b forces the COPY command into
binary mode, the filename is the file to be updated, the + (plus sign)
indicates that a file is to be appended, and the ,, (commas) are
placeholders for the remaining parameters (which are not included in
this example). Because the file to be appended is not specified, the
COPY command will append nothing and only update the time and date
stamps for the file.
The following batch file, TOUCH.BAT, can be used to automate the
process:
#echo off
if %1.==. goto end
if not exist %1 goto end
copy /b %1 +,, > nul
echo %1 touched!
:end
This batch file requires one parameter, the file to be "touched." If the
parameter is not supplied, line 2 will cause the batch file to
exit without doing anything. If the specified file does not exist,
line 3 will cause the batch file to exit also.
2. Touch.cmd
#echo off
:: -----------------------------------------
:: Process input parameter
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if "%1%"=="" goto help
:: -----------------------------------------
:: Update Modified Date property to now
:: -----------------------------------------
if not exist %1% goto end
copy /b %1% +,, > nul
echo %1 touched!
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to update the Modified Date property
echo of teh specified file to the current
echo date and time.
echo.
echo Syntax: touch filename
echo where,
echo filename is the name of the name of the file to "touch."
echo filename may include a relative o full path.
echo filename may include wild cards like *.txt.
echo.
:end
3. MidasTouch.cmd
#echo off
:: -----------------------------------------
:: Find files older than specified date
:: -----------------------------------------
:: -----------------------------------------
:: Default Values
:: -----------------------------------------
set "default_path=%cd%"
set "default_err_log=%cd%\midastouch_err.log"
set /a default_date=-365
set "open_log=False"
set "recurse=True"
:: -----------------------------------------
:: Process input parameters
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if /I "%1%"=="help" goto help
set "dir_in="
set "err_log="
set "dd="
:: Read in commandline arguements.
echo Arguements:
:arguement_loop
if "%1%"=="/p" (
echo Path: %2%
set dir_in=%2%
shift
goto loop_bottom)
if "%1%"=="/l" (
echo Error log: %2%
set err_log=%2%
shift
goto loop_bottom)
if "%1%"=="/-l" (
echo No error log. Output to console.
set err_log=CON
shift
goto loop_bottom)
if "%1%"=="/d" (
echo Date: %2%
set /a dd=%2%
shift
goto loop_bottom)
if "%1%"=="/o" (
echo Open log: True
set "open_log=True"
goto loop_bottom)
if "%1%"=="/-o" (
echo Open log: False
set "open_log=False"
goto loop_bottom)
if "%1%"=="/s" (
echo Recursive: True
set "recurse=True"
goto loop_bottom)
if "%1%"=="/-s" (
echo Recursive: False
set "recurse=False"
goto loop_bottom)
if not "%1%"=="" (
if "%dir_in%"=="" (
echo Path: %1%
set dir_in=%1%
goto loop_bottom)
if "%err_log%"=="" (
echo Error log: %1%
set err_log=%1%
goto loop_bottom)
if "%dd%"=="" (
echo Date: %1%
set /a dd=%1%
goto loop_bottom)
)
:loop_bottom
shift
if not "%1%"=="" goto arguement_loop
if "%dir_in%"=="" (
set dir_in=%default_path%)
if "%err_log%"=="" (
set err_log=%default_err_log%)
if "%dd%"=="" (
set /a dd=%default_date%)
:: -----------------------------------------
:: Execution
:: -----------------------------------------
:: Write header
set "header=Touch_dir.cmd Error Log"
if exist %err_log% (
del /q %err_log%)
#echo %header% >%err_log%
set cmd_str="cmd /c copy /b #path +,,"
:: Update Modified Date property to now
if /I "%recurse%"=="True" (
set cmd_str=forfiles /s /p %dir_in% /d %dd% /c %cmd_str%
) else (
set cmd_str=forfiles /p %dir_in% /d %dd% /c %cmd_str%
)
echo Command: %cmd_str% >>%err_log%
echo Errors: >>%err_log%
echo. >>%err_log%
echo Executing command: %cmd_str%
#echo Updating Modified Date of files older than date: %dd%.
#echo This may take a while. Please be patient...
#echo.
echo.
set cmd_str=%cmd_str% || #echo Failed to update: #path >>%err_log%"
%cmd_str%
:: Results
#echo Error log: %err_log%
if "%open_log%"=="True" (start %err_log%)
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch_dir.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to recursively "touch" all files in a
echo folder to update their Modified Date property to the current
echo date and time.
echo.
echo Syntax: touch_dir /d directory /l err_log /m months
echo where,
echo /p path Path containing files with Modified
echo Date values to update to now.
echo (default = current directory).
echo /s (or /-s) Recursive (or not recursive) search
echo (default recursive is %recurse%).
echo /l err_log Error log: list of files not updated
echo (default err_log: midastouch_err.log).
echo /o (or /-o) Open (or do not open) error log after
echo execution (default open_log: %open_log%).
echo /d date Selects files with a last modified date greater
echo than or equal to (+), or less than or equal to
echo (-), the specified date using the
echo "MM/dd/yyyy" format; or selects files with a
echo last modified date greater than or equal to (+)
echo the current date plus "dd" days, or less than or
echo equal to (-) the current date minus "dd" days. A
echo valid "dd" number of days can be any number in
echo the range of 0 - 32768.
echo "+" is taken as default sign if not specified.
echo (default date is: %default_date%).
echo.
:end
Just to add that the same source provide a batch script.
#echo off
goto start
:usage
echo usage: TOUCH.BAT "MYFILENAME"
exit /b 0
:start
if %1.==. goto usage
if not exist %1 goto usage
copy /b %1 +,, > nul
echo %1 touched!
exit /b 0

Resources