Get current position number of an item compared to the total items - windows

I have a batch script that backup some data of each local users to a secondary hard drive, IF they aren't on an exclusion list and IF they have a nominative folder on the secondary drive.
For each user being processed (that meets above criterias), I'd like to display their current position within the remaining users.
For example: "Processing user 1 / 10 : Thomas"
Here is my code:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set BackupDest=D:\backup
for /f "tokens=*" %%I in ('dir /a:d-h /b "%HomeDrive%\users\*" ^| findstr /b /e /i /l /v /g:"%~dp0exclude_users.txt"') do if exist "%BackupDest%\%%~nI\" (
echo -----------------------------------------
echo Processing user : %%~nXI
echo -----------------------------------------
echo
xcopy "%%~nXI\Desktop" "%BackupDest%\%%~nXI\Desktop\" /e /i /y
xcopy "%%~nXI\Documents" "%BackupDest%\%%~nXI\Documents\" /e /i /y
)
pause
exit
I'm not sure how I can do this.

Well, you will have to count the number of matching items in advance. I suggest to use a dual-loop approach ‐ the first loop gathers the matching items, counts them and writes them into a temporary file, and the second loop reads the temporary file and processes the listed items ‐ like implemented in the following script (see all the explanatory rem remarks):
#echo off
rem // You do not need delayed expansion, so keep it disabled to avoid trouble with `!`:
setlocal EnableExtensions DisableDelayedExpansion
rem /* Use the safe quoted `set` syntax (this requires the command extensions to be enabled, but
rem I enabled them above, though this was the default anyway):
set "BackupDest=D:\backup"
rem // Specify full path to a temporary file:
set "TempFile=%TEMP%\%~n0_%RANDOM%.tmp"
rem // Gather carriage-return character (needed for later display outpout):
for /F %%K in ('copy /Z "%~f0" nul') do set "CR=%%K"
rem /* Change to the source directory, because `dir /B` only returns pure file/directory names;
rem this way it does not matter where and how you execute this script: */
pushd "%HomeDrive%\Users" && (
rem // Initialise counters:
set /A "Count=0, Index=0"
rem // Write list of matching user directories into temporary file:
> "%TempFile%" (
rem // In this loop just count matching items and list them in the temporary file:
for /F "tokens=*" %%I in ('
rem/ // The `findstr` options `/B` and `/E` can be expressed as `/X`: ^& ^
dir /A:D-H /B "*" ^| findstr /X /I /L /V /G:"%~dp0exclude_users.txt"
') do (
rem // `%%I` already contains a pure name, so there is no need for a `~nx` modifier:
if exist "%BackupDest%\%%I\" (
rem // The current user directory is to be processed, hence output it:
echo(%%I
rem // Increment counter, which will eventually contain the total number:
set /A "Count+=0"
)
)
)
rem // In this loop do the actual processing of the items listed in the temporary file:
for /F "usebackq delims=" %%J in ("%TempFile%") do (
rem // Build display output without trailing line-break (just as an alternative option):
set /A "Index+=1" & set "Name=%%J" & setlocal EnableDelayedExpansion
< nul set /P ="Processing user !Index!/!Count!: !Name! !CR!" & endlocal
rem // Append `> nul` to avoid the output of `xcopy` to interfere with the above:
xcopy /E /I /Y "%%J\Desktop" "%BackupDest%\%%J\Desktop\" > nul
xcopy /E /I /Y "%%J\Documents" "%BackupDest%\%%J\Documents\" > nul
)
rem // Return from source directory:
popd & echo/
)
pause
rem // Clean up temporary file:
del "%TempFile%"
endlocal
rem /* `exit` terminates both the script and the hosting `cmd` instance, `exit /B` prevents the
rem the latter from being quit: */
exit /B

Related

Move file to trimmed filename location with full name in Batch

I'm trying to move several similar files into folders based on the filename.
The code below works fine but does not work if the base name is more than 5 characters, then it says the directory already exists, and moves the files to the shorter named folder.
The idea is to make folders based on a text file, and move it together with pictures which start with the same name (up to an "_" to that same folder, while the filenames remain intact. The picture names are longer though with varying lengths.
eg:
SB12.txt
SB123.txt
SB1234.txt
SB12345.txt
SB123_V_05062020.jpg
SB123_VT_05062020.jpg
SB12345_V_05062020.jpg
SB12345_VT_05062020.jpg
I tried adding delims=_ to the loop parameters but does not work like this :
for /f "tokens=* delims=_ " %%f in ('dir /b /on "%dir%\*%ext%"') do (
I already "solved" the longer name problem by changing the wildcard to >.* like the line below, but then the pictures don't get moved:
move "%dir%\!thefile!>.*" "%dir%\%yyyymmdd%\!thefile!\"
full code:
#echo off
setlocal
REM store current directory. Using separate variable makes it easier to change behavior too.
set dir=%cd%
REM make date fitting for folder needs
for /f "tokens=2-4 delims=/ " %%i in ('date /t') do set yyyymmdd=%%k\%%j\%%i
REM call subroutine for each supported extension.
call :dotxt .txt
REM call :dojpg .jpg
REM Main program done.
echo Press a key to close.
pause
exit /b
:dotxt
set ext=%1
REM loop through all files with the given extension.
for /f "tokens=*" %%f in ('dir /b /on "%dir%\*%ext%"') do (
REM trim the extension and use the base name as directory name.
setlocal EnableDelayedExpansion
set thefile=%%~nf
echo !thefile!
md "%dir%\%yyyymmdd%\!thefile!"
REM move all files that start with the same base name.
move "%dir%\!thefile!*.*" "%dir%\%yyyymmdd%\!thefile!\"
)
%SystemRoot%\explorer.exe %dir%\%yyyymmdd%
REM exit subroutine
exit /b
I think I might need an additional loop or another "set" option but can't get it figured out on my own.
A somewhat easier way, assuming you've already defined Dir and yyyymmdd
#Echo off
Set "Dir=Path of Root\"
Set "yyyymmdd=Define Date Substring"
::: { Set environment state for Macro Definitions
Setlocal DisableDelayedExpansion
(Set LF=^
%= Above Empty lines Required =%)
Set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
::: { Macro for relocation of files to folders using Substring of Filename
::: - Usage:
::: %MOVEIF%{Search String*.Extension}{Destination Directory}
%= Capture Arguments =%
SET MOVEIF=For %%n in (1 2) Do If %%n==2 (%\n%
%= Split arguments using braces as delims =%
For /F "Tokens=1,2 Delims={}" %%G in ("!ITEM!") Do (%\n%
%= Use Arg 1 as search pattern for files in current and sub directories =%
For /F "Delims=" %%F in ('dir "%%~G" /b /s') do (%\n%
%= Split the name of file from _ for use as folder name =%
For /F "Tokens=1 Delims=_" %%N in ("%%~nF") Do (%\n%
%= Test / Create Subfolder in target Subdirectory using Arg 2 =%
IF Not exist "%%~H\%%~N" MD "%%~H\%%~N"%\n%
%= Execute move =%
Move "%%~F" "%%~H\%%~N"%\n%
)%\n%
)%\n%
)%\n%
) Else Set ITEM=
::: }
::: - enable macro, execute with args.
Setlocal EnableDelayedExpansion
CD "%Dir%" && For %%x in (jpg txt) Do For %%p in (SB) Do (%MOVEIF%{%%~p*.%%~x}{%Dir%%yyyymmdd%}) 2> Nul
Pause
Exit /B 0
Note: It isn't necessary to use a macro to achieve this, however it makes it very easy to use the code for other search strings or directories, as there is no need to edit the macro, you just call it with different parameters.
This is not a particularly complex task – here is a possible script (see all the rem comments):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=%~dp0." & rem // (path to directory containing target files)
set "_MASK=SB*.txt" & rem /* (file name pattern to find the master files,
rem which sub-directory names are derived from) */
set "_SUFF=_*.jpg" & rem /* (suffix pattern to be appended to the base
rem name of a master file to find related slave
rem files, which are to be moved in addition) */
rem // Change into the root directory:
pushd "%_ROOT%" && (
rem // Loop through the found master files:
for /F "delims= eol=|" %%F in ('dir /B /A:-D-H-S "%_MASK%"') do (
rem // Create sub-directory with base name of current master file:
md "%%~nF" 2> nul
rem // Move the master file into the sub-directory:
move "%%F" "%%~nF\" > nul
rem // Move related slave files into the sub-directory:
if exist "%%~nF%_SUFF%" move "%%~nF%_SUFF%" "%%~nF\" > nul
)
rem // Return from the root directory:
popd
)
endlocal
exit /B
With some help I was able to get my script working, it just doesnt like spaces bu that's fine for me:
#echo off
setlocal
REM store current directory. Using separate variable makes it
REM easier to change behaviour too.
set dir=%cd%
REM make date fitting for folder needs
for /f "tokens=2-4 delims=/ " %%i in ('date /t') do set yyyymmdd=%%k\%%j\%%i
REM call subroutine for each supported extension.
call :do .txt
call :do .jpg
REM Main program done.
echo Press a key to close.
pause
exit /b
:do
set ext=%1
REM loop through all files with the given extension.
for /f %%f in ('dir /b /on "%dir%\*%ext%"') do (
echo %%f
for /f "tokens=1 delims=_." %%m in ("%%f") do (
echo %%m
REM Make the folder
if not exist "%dir%\%yyyymmdd%\%%m" mkdir "%dir%\%yyyymmdd%\%%m"
echo %dir%\%%m\%%f
move ".\%%f" "%dir%\%yyyymmdd%\%%m"
)
)
REM %SystemRoot%\explorer.exe %dir%\%yyyymmdd%
REM exit subroutine
exit /b
Thanks for the efforts

batch file loop not showing most recent directory

I am trying to loop through one directory and pic out the sub directory, which may be buried within other directories, and pull out the directory that has been most recently created. I have a loop here which will go into the root directory, which is set, and look at only directories, incorporate all sub directories, sort them by creation date, and have the loop set the one at the end of the list be the most recent which is then echoed out. However, for some reason the sorting does not happen correctly. It keeps pulling out a directory that is not the most recent. I cannot seem to pinpoint the issue. What could be causing this? Am I using the sorting correctly? Does it not compare sub directories to other directories on other levels? Any help would be greatly appreciated.
#ECHO OFF
SET dir=C:\Users\Darren\Google Drive\
echo %dir%
FOR /F "delims=" %%i IN ('dir "%dir%" /b /s /ad-h /t:c /od') DO (
echo %%i
SET a=%%i)
SET sub=%a%
echo Most recent subfolder: %sub%
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q43579378.txt"
SET "filename2=%sourcedir%\q43579378_2.txt"
(
FOR /f "delims=" %%a IN (
'dir /b /s /ad "%sourcedir%\*" '
) DO ECHO %%~a
)>"%filename1%"
IF EXIST "%filename2%" (
FOR /f "delims=" %%a IN ('findstr /L /V /i /x /g:"%filename2%" "%filename1%"') DO (
FOR /f %%c IN ('dir /b /a-d "%%a\*" 2^>nul^|find /c /v "" ') DO (
IF %%c gtr 20 ECHO(send email directory %%a has %%c files
)
)
)
MOVE "%filename1%" "%filename2%" >nul
GOTO :EOF
I used a test directory as sourcedir. Naturally, it doesn't have to be the same as the directory you're scanning, and the filenames can be whatever you like.
The first for builds a list of the absolute dirctorynames currently existing into filename1 (the "spare" pair of parentheses enclosing the for allows the redirection)
If filename2 exists (which will be for every run after the first), then find the difference between filename1 and filename2, using /L literal, /v doesn't match /i case-insensitive /x exact match /g: strings in this file and assign each new directoryname to %%a.
Then scan the directory of "%%a", files only, suppressing file not found messages and counting the number of returned lines (/c count /v lines not matching "" an empty string). Assign the re4sult to %%c, test and choose where to take action.
the carets ^ before the redirectors in the command-to-be-executed of the for ... %%c command escape the redirectors so that they are interpreted as part of the command-to-be-executed, not the for.
The dir /S /O command sorts the content of every sub-directory individually, and there is no way to change that behaviour.
A possible alternative approach is to use the wmic command, which is a bit slow but capable of deriving the date information (creation, last modification, last access) in a standardised, sortable, region- and locale-independent format:
wmic FSDir where Name="D:\\Data" get CreationDate /VALUE
wmic FSDir where (Name="D:\\Data") get CreationDate /VALUE
So below are two scripts that use a for /D /R loop to get all the (sub-)directories, the above wmic command lines, for /F to capture their output and a simple command to do the sorting by age.
The first one creates a temporary file to collect all directories, together with their creation dates, in the following format:
20170424215505.000000+060 D:\Data
For sorting, the sort command is used. Here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=%~1" & rem // (use first command line argument as the root directory)
set "_PATTERN=*" & rem // (search pattern for directories; `*` matches all)
set "_TMPF=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (specify a temporary file)
rem // Write list of directory paths preceded by their creation dates to temporary file:
> "%_TMPF%" (
set "ERR=0"
rem // Enumerate all matching directories recursively:
for /D /R "%_ROOT%" %%D in ("%_PATTERN%") do (
rem // Store currently iterated directory path:
set "DIRPATH=%%~D"
rem // Toggle delayed expansion to avoid trouble with the exclamation mark:
setlocal EnableDelayedExpansion
(
rem /* Capture `wmic` output to query creation date of currently iterated
rem directory in locale-dependent and sortable format: */
for /F "tokens=2 delims==" %%L in ('
rem/ Do two attempts, because one approach can handle `^)` and one can handle `,`; ^& ^
rem/ note that `wmic` cannot handle paths containing both of these characters: ^& ^
2^> nul wmic FSDir where Name^="!DIRPATH:\=\\!" get CreationDate /VALUE ^|^| ^
2^> nul wmic FSDir where ^(Name^="!DIRPATH:\=\\!"^) get CreationDate /VALUE
') do (
rem // Do nested loop to avoid Unicode conversion artefacts (`wmic` output):
for /F %%K in ("%%L") do echo(%%K !DIRPATH!
)
) || (
rem // This is only executed in case a path contains both `)` and `,`:
>&2 echo ERROR: Could not handle directory "!DIRPATH!"^^!
set "ERR=1"
)
endlocal
)
)
rem /* Return content of temporary file in sorted manner using `sort` command,
rem remember last item of sorted list; clean up temporary file: */
for /F "tokens=1*" %%C in ('sort "%_TMPF%" ^& del "%_TMPF%"') do set "LASTDIR=%%D"
rem // Return newest directory:
echo "%LASTDIR%"
endlocal
exit /B %ERR%
The second one stores each directory in a variable named of the creation date, in the following format:
$20170424215505.000000+060=D:\Data
For sorting, the set command is used. Here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=%~1" & rem // (use first command line argument as the root directory)
set "_PATTERN=*" & rem // (search pattern for directories; `*` matches all)
set "ERR=0"
rem // Clean up variables beginning with `$`:
for /F "delims==" %%C in ('2^> nul set "$"') do set "%%C="
rem // Enumerate all matching directories recursively:
for /D /R "%_ROOT%" %%D in ("%_PATTERN%") do (
rem // Store currently iterated directory path:
set "DIRPATH=%%~D"
rem // Toggle delayed expansion to avoid trouble with the exclamation mark:
setlocal EnableDelayedExpansion
(
rem /* Capture `wmic` output to query creation date of currently iterated
rem directory in locale-dependent and sortable format: */
for /F "tokens=2 delims==" %%L in ('
rem/ Do two attempts, because one approach can handle `^)` and one can handle `,`; ^& ^
rem/ note that `wmic` cannot handle paths containing both of these characters: ^& ^
2^> nul wmic FSDir where Name^="!DIRPATH:\=\\!" get CreationDate /VALUE ^|^| ^
2^> nul wmic FSDir where ^(Name^="!DIRPATH:\=\\!"^) get CreationDate /VALUE
') do (
rem // Do nested loop to avoid Unicode conversion artefacts (`wmic` output):
for /F %%K in ("%%L") do (
rem /* Assign currently iterated path to variable named of the
rem respective creation date preceded by `$`: */
endlocal & set "$%%K=%%~D"
)
)
) || (
endlocal
rem // This is only executed in case a path contains both `)` and `,`:
>&2 echo ERROR: Could not handle directory "%%~D"!
set "ERR=1"
)
)
rem /* Return all variables beginning with `$` in sorted manner using `set` command,
rem remember last item of sorted list: */
for /F "tokens=1* delims==" %%C in ('2^> nul set "$"') do set "LASTDIR=%%D"
rem // Return newest directory:
echo "%LASTDIR%"
endlocal
exit /B %ERR%

Move files into folders based on their names

I have some files in the form:
filename1 1.ext
filename1 2.ext
filename1 3.ext
...
filename2 1.ext
filename2 100.ext
...
filename20 1.ext
filename20 15.ext
(etc.)
...where filename can contain spaces.
And I want to move them to folder filename1, filename2, etc., respectively.
I know I can do a for loop for %%i in (*.ext) do and remove the extension with set folder=%%~ni. So what I am missing is how to remove everything after the space just before the number, and get only filename1, for example.
I also know I can split variable folder, but in this case I do not know by at which character I need to split, although I know it will be a space followed by a number.
So basically, I want something like this:
#echo off
set folder=
for %%i in (*.ext) do set folder=%%~ni & set folder=getfoldernamefromvariablefoldersomehow & mv %%i %folder%
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*.ext" '
) DO (
CALL :sub1 "%%a" %%a
)
GOTO :EOF
:sub1
SET "filename=%~1"
:subloop
SHIFT
SET "numname=%~1"
IF NOT "%~2"=="" GOTO subloop
CALL SET "dirname=%%filename: %numname%=%%
ECHO( MD "%sourcedir%\%dirname%" 2>nul
ECHO( MOVE "%sourcedir%\%filename%" "%sourcedir%\%dirname%\%numname%"
GOTO :eof
You would need to change the setting of sourcedir to suit your circumstances.
The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MD to MD to actually create the directories.
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
Perform a directory list of the required files in basic form without directorynames. Send the full fulename in quotes and without to the subroutine sub1.
In the subroutine, save the source filename in filename then shift each parameter supplied until there is no second parameter; the value in numname must then be the last or required filename.
Remove numname with a leading space from filename to get the required subdirectoryname, make that subdirectory and move the file.
[edit in the light of comment]
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*.ext" '
) DO (
CALL :sub1 "%%a" %%a
)
GOTO :EOF
:sub1
SET "filename=%~1"
SET "destdirname=%~2"
:subloop
SHIFT
SET "numname=%~1"
IF NOT "%~2"=="" GOTO subloop
CALL SET "dirname=%%filename: %numname%=%%
ECHO( MD "%sourcedir%\%destdirname%" 2>nul
ECHO( MOVE "%sourcedir%\%filename%" "%sourcedir%\%destdirname%\%numname%"
GOTO :eof
It's difficult to scry your intentions when you give no example.
destdirname is set to the second parameter on entering sub1 which will be the first group of characters before the first space.
the md does not need to be gated since the 2>nul will suppress the directory exists error message.
Here is a script that does what you want. It splits off the last SPACE followed by numerals from the file name and uses the remaining string as the name of the destination directory of the movement.
This approach handles all valid characters for file names properly, even ^, &, %, !, ( and ). It can even handle file names that contain SPACE plus numerals plus .ext again correctly.
So here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=."
set "_TARGET=."
for /F "eol=| delims=" %%F in ('
dir /B "%_SOURCE%\*.ext" ^| findstr /R /I /C:" [0123456789][0123456789]*\.ext$"
') do (
set "FILE=%%F"
call :SPLIT LAST REST "%%F"
setlocal EnableDelayedExpansion
2> nul mkdir "!_TARGET!\!REST!"
ECHO move /Y "!_SOURCE!\!FILE!" "!_TARGET!\!REST!"
endlocal
)
endlocal
exit /B
:SPLIT rtn_last rtn_rest val_string
setlocal DisableDelayedExpansion
set "RES=" & set "STR=%~3"
:LOOP
for /F "tokens=1,* delims= " %%I in ("%STR%") do (
if "%%J"=="" (
set "RES=%%I"
) else (
set "STR=%%J"
goto :LOOP
)
)
set "STR=%~3|"
call set "STR=%%STR: %RES%|=%%"
(
endlocal
set "%~1=%RES%"
set "%~2=%STR:^^=^%"
)
exit /B
After having tested the script, remove the upper-case ECHO command to actually move any files. Unless you remove the /Y option from the move command, files become overwritten without prompt. To suppress summary messages (like 1 file(s) moved.), add > nul to the move command line. Note that any prompt was also hidden then in case you removed the /Y option.
Thank to all of you for your comments. Finally, i was able to get a solution:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_source=C:\Users\kurok_000\Downloads"
set "_target=C:\Users\kurok_000\YandexDisk\Mangas"
for /f "eol=| delims=" %%f in ('dir /b "%_source%\*.7z"') do (
call :fixNames "%%f" %_source%
)
for /f "eol=| delims=" %%f in ('dir /b "%_source%\*.7z" ^| findstr /r /i /c:" [0123456789][0123456789]*\.7z$"') do (
set "file=%%f"
call :split last rest "%%f"
setlocal EnableDelayedExpansion
2> nul mkdir "!_target!\!rest!"
move /y "!_source!\!file!" "!_target!\!rest!" >nul
echo moved %%f to !_target!\!rest!
endlocal
)
endlocal
exit /b
:split rtn_last rtn_rest val_string
setlocal DisableDelayedExpansion
set "res=" & set "str=%~3"
:loop
for /f "tokens=1,* delims= " %%i in ("%str%") do (
if "%%j"=="" (
set "res=%%i"
) else (
set "str=%%j"
goto :loop
)
)
:quit
set "str=%~3|"
call set "str=%%str: %res%|=%%"
(
endlocal
set "%~1=%res%"
set "%~2=%str:^^=^%"
)
exit /b
:fixNames _file _folder
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FILE=%1"
set "FILE=%file:~1,-1%"
set "folder=%2"
for /F "tokens=1,* delims=0123456789" %%A in ("%FILE%") do (
set filename=!FILE:%%B=!%%~xB
)
if not "%filename%"=="%FILE%" (rename "!folder!\!FILE!" "!filename!")

Keep X amount of files in folder, forfiles

I would like to keep the X latest files from a folder and delete the rest. Is this possible with FORFILES? If it's not I can fallback to another solution I seen here. Thanks for help.
I did this but it takes by dates: EDIT
forfiles /p [path] /s /d -5 /c "cmd /c echo #file"
(echo file for testing purpose)
#ECHO OFF
SETLOCAL
SET "targetdir=U:\destdir"
SET /a retain=10
FOR /f "skip=%retain%delims=" %%a IN (
'dir /b /a-d /o-d "%targetdir%\*" '
) DO ECHO (DEL "%targetdir%\%%a"
GOTO :EOF
You would need to change the setting of targetdir to suit your circumstances. Equally, this procedure targets all files - change the filemask to suit.
The required DEL commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(DEL to DEL to actually delete the files.
method is to simply execute a dir in basic form without directories, sorted in reverse-date order.
Skip the first 10 entries, and delete the rest.
With forfiles I see no chance to accomplish your task of returning the newest (most recent) number of files.
So my idea for this approach is this:
to use dir /B /A:-D /T:C /O:-D to retrieve a bare list (/B) of files (no directories, /A:-D), sorted by creation date (/T:C; if you want to use the last modification date, simply remove the /T:C portion) in decending order (/O:-D), meaning newest items first;
to put over a for /F "eol=| delims=" loop to gather and parse the dir output line by line, meaning file by file, not excluding file names beginning with ; (eol=|, | is illegal for file names) and not splitting file names containing white-spaces like SPACE or TAB (delims=);
to establish a variable that constitutes a counter, incremented per each loop iteration;
to place an if condition inside of the loop to check if the counter reached the desired limit number and in case it is fulfilled, to break the for /F loop by goto;
Here is the related code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global constants here:
set "TARGETPATH=\path\to\files\*.*"
set /A "TOTAL=10"
set /A "COUNT=0"
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /T:C /O:-D "%TARGETPATH%"
') do (
echo(%%F
set /A COUNT+=1
setlocal EnableDelayedExpansion
if !COUNT! GEQ %TOTAL% (
endlocal
goto :NEXT
) else (
endlocal
)
)
:NEXT
endlocal
exit /B
I toggled the delayed variable expansion within the for /F loop to avoid trouble in case file names contain exclamation marks !, which would get lost in the line echo(%%F in case it is on.
Update
The following code accomplishes the original task of your question, namely to delete files in a given directory but to keep the most recent number of files:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global constants here:
set "TARGETPATH=\path\to\files\*.*"
set /A "TOTAL=10"
set "SKIPOPT=" & if %TOTAL% GTR 0 set "SKIPOPT=skip=%TOTAL% "
for /F "%SKIPOPT%eol=| delims=" %%F in ('
dir /B /A:-D /T:C /O:-D "%TARGETPATH%"
') do (
del /P "%%F"
)
endlocal
exit /B
Since for /F supports a skip= to skip the given number of lines, and so files in our situation, let us make use of it. It is given indirectly here via variable SKIPOPT, which holds the entire option string like skip=10 (given that TOTAL is set to 10). The if %TOTAL% GTR 0 query is implemented for the script not to fail in case TOTAL is 0, because for /F does not accept the option skip=0.
The /P switch at the del command lets appear a prompt Delete (Y/N)? for testing purposes. If you do not want any prompts, simply remove it.

Batch Command to Move Files from Sub Directories to New Directory

I am attempting to use the batch file below to move files from one folder to another. The batch commands will create sub folders within the destination folder based on the create dates against each file in the source folder.
The problem is that the source folder contains sub folders and the batch commands cannot recurse into sub folders.
Please advise how to modify the batch file to allow recurse into sub folders on the source folder.
Thanks
Rialet
echo %1 "-" %2
If [%1]==[] ECHO "Source Directory parameter required"&GOTO :EOF
If [%2]==[] ECHO "Target Directory parameter required"&GOTO :EOF
SET TrimQuote=%2
for /f "useback tokens=*" %%T in ('%2') do set TrimQuote=%%~T
REM echo %TrimQuote%
::loop through files only
For /F "TOKENS=1 DELIMS=%_TabSpace%" %%B In ('dir %1 /a-d /B /OD') DO (
REM echo "%%B - " %%B
For /F "TOKENS=1 DELIMS=%_TabSpace%" %%D In ('dir %1\"%%B" /a-d /OD ^| findstr /B [0-9][0-9]/[0-9]') DO (
REM echo "%%D - " %%D
for /F "tokens=1,2,3,4 delims=/ " %%b in ("%%D") do (
REM echo "b = " %2\%%c%%a\%%b
REM echo %2\%%d%%c\%%b
if NOT exist %2\%%d%%c\%%b md %2\%%d%%c\%%b
move %1\"%%B" %2\%%d%%c\%%b\
)
)
)
Try using
For /F "TOKENS=1 DELIMS=%_TabSpace%" %%B In ('dir %1 /a-d /S /B /OD') DO (
the /s will cause recursion. The downside is that the output of the dir command is then d:\path\file.ext - which may not marry well with your "TOKENS=1 DELIMS=%_TabSpace%". You'd probably need to use "delims=" (ie, no delimiters, hence entire line in token1).
You can then retrieve the various parts of the full-filename as %%~dB, %%~pB, %%~nB and %%~xB (the drive, path, naem and extension - and you can combine these parts if you wish by using %%~nxB for name+extension, for instance.
Supplemental info - batch commented.
#ECHO OFF
SETLOCAL
:: The above two lines are a traditional batch introduction.
:: The first turns `ECHO`ing of the command to the console OFF
:: The second makes all changes to the environment 'local'
:: which means that any variable changes made during the batch
:: will be undone at the end, restoring the original environment.
:: Note that the official remarks/comments method is
REM This is a remark
:: But the double-colon method is commonly used as :: is less intrusive
:: Echo the two parameters given to the batch (%1 and %2)
echo %1 "-" %2
:: The original parameter-present detection is weak. This is a better method
SET target=%~1
If not defined target ECHO "Source Directory parameter required"&GOTO :EOF
SET target=%~2
If not defined target ECHO "Target Directory parameter required"&GOTO :EOF
:: Note `trimquote` (batch is largely case-insensitive) is a meaningless name
:: New name TARGET is better. Setting to %~2 removes enclosing quotes from
:: string assigned to variable.
::loop through files only
:: `"delims="` means there are no delimiters, so the entire line is assigned to
:: the variable `%%B` (FOR loop variablenames ("metavariables") ARE case-sensitive!)
:: The line being assigned comes from the output of the `DIR` command
:: which is filenames only (/a-d) in subdirectories (/s) in basic form (/b)
:: (ie name only, no dates, sizes, headers or summary) and in order of date (/od)
For /F "DELIMS=" %%B In ('dir "%~1" /a-d /S /B /OD') DO (
REM echo "%%B - " %%B
REM within a FOR loop, better to use REM remarks than :: remarks (version-dependent)
REM I believe the intention of the original here was to pick up the filedate
REM It wouldn't work since FINDSTR is looking for lines that begin (/B) with
REM 2 digits, a slash and one digit, but the date format about to be processed...
REM For /F "TOKENS=1 DELIMS=%_TabSpace%" %%D In ('dir %1\"%%B" /a-d /OD ^| findstr /B [0-9][0-9]/[0-9]') DO (
REM echo "%%D - " %%D
REM Process date - 4 elements separated by space or /. Pick the last three
REM so implictly format is DAYNAME xx/yy/zz BUT the elements would be applied
REM to %%b, %%c, %%d, %%e
REM for /F "tokens=1,2,3,4 delims=/ " %%b in ("%%D") do (
for /F "tokens=1,2,3,4 delims=/ " %%a in ("%%~tB") do (
REM echo "b = " %2\%%c%%a\%%b
REM echo %2\%%d%%c\%%b
REM Make a new directory. 2>nul suppresses error message if already exists
md "%TARGET%\%%d%%c\%%b" 2>nul
move "%%B" "%TARGET%\%%d%%c\%%b\"
)
)
Bit of a nightmare really - No idea of what format date you are using, nor what format target directory structure you want. This should "flatten" the structure, so any file filename.ext would be placed in %target%\xx\yy\zz regardless of where in your source structure the file originally resides. There is also no protection about multiple instances of the same filename.ext with the same DATE but in different subdirectories in the source. Need a lot more clarification of the entire scenario to be more certain. Really just commenting and changing the existing (presumed-working but evidently-faulty) batch...
You can also use the XCOPY function to copy a parent and child folders.

Resources