Removing a "sample.ext.ext2" file that has no "sample.ext" file associated with it - windows

The application creates .mta files (with exactly same name) of all multimedia files in my HDD. What I want to do is to check all sub-folders of root folder if there is no multimedia file associated with some .mta then delete it.
Detailed example. Lets say we have files
01.mp3
01.MP3.mta
02.mkv
02.MKV.mta
03.jpg
03.JPG.mta
04.MP4.mta <<==
As you see the last .mta has no original file. I want to delete last file.
I don't know if it's possible with cmd. But following function doesn't work. Please take a look
For /r %%i in (*.mta) do call :nomta %%i
pause
goto end
:nomta
set stem=%1:.mta=%
set original=%stem%.mta
if not exist %original% do exit /B
if not exist %stem% do del /a /Q %1
goto :EOF
:end
echo done
PAUSE

You can use a for command to do this with dir /a feeding it both hidden and non-hidden filenames. Here's an example:
C:\temp\z\z>attrib *
A C:\temp\z\z\foo.bar.mta
A H C:\temp\z\z\h2.mp4.mta
A C:\temp\z\z\hid.mp4
A H C:\temp\z\z\hid.mp4.mta
A C:\temp\z\z\zoo.bar
A C:\temp\z\z\zoo.bar.mta
C:\temp\z\z>for /f %F in ('dir /b/a *.mta') do if not exist "%~nF" echo %F >> z
C:\temp\z\z>type z
foo.bar.mta
h2.mp4.mta
so replacing the echo with a del should achieve your target.

Related

Loop through files in a folder and check if they have different extensions

I have a folder that contains files; each document should have .pdf and .xml format. I need to write a BAT file to run from a scheduled task to verify that both documents exist for each.
My logic is:
loop through files in the folder
strip each file to its name without extension
check that same name files exist for both .xml and pdf.
if not mark a flag variable as problem
when done, if the flag variable is marked, send an Email notification
I know how to use blat to sending email, but I'm having trouble to execute the loop. I found a way to get path and file name without extension but can't merge them.
I've used batch files a few time, before but I'm far from an expert. What am I missing?
Here's the code I have so far:
set "FolderPath=E:\TestBat\Test\"
echo %FolderPath%
for %%f in (%FolderPath%*) do (
set /p val=<%%f
For %%A in ("%%f") do (
Set Folder=%%~dpA
Set Name=%%~nxA
)
echo Folder is: %Folder%
echo Name is: %Name%
if NOT EXIST %FolderPath%%name%.xml
set flag=MISSING
if NOT EXIST %FolderPath%%name%.pdf
set flag=MISSING
)
echo %Flag%
pause
There is no need for fancy code for a task such as this:
#Echo Off
Set "FolderPath=E:\TestBat\Test"
If /I Not "%CD%"=="%FolderPath%" PushD "%FolderPath%" 2>Nul||Exit/B
Set "flag="
For %%A In (*.pdf *.xml) Do (
If /I "%%~xA"==".pdf" (If Not Exist "%%~nA.xml" Set "flag=MISSING")
If /I "%%~xA"==".xml" (If Not Exist "%%~nA.pdf" Set "flag=MISSING")
)
If Defined flag Echo=%flag%
Timeout -1
Something like this :
set "FolderPath=E:\TestBat\Test\"
pushd "%FolderPath%"
for %%a in (*.xml) do (
if exist "%%~na.pdf"(
echo ok
) else (
rem do what you want here
echo Missing
)
)
popd
Is this what you want?
#echo off
setlocal enabledelayedexpansion
set "FolderPath=E:\TestBat\Test\"
echo !FolderPath!
for /f "usebackq delims=" %%f in (`dir !FolderPath! /B`) do (
set /p val=<%%f
For %%A in ("%%f") do (
Set Folder=%%~dpA
Set name=%%~nxA
)
echo Folder is: !Folder!
echo Name is: !name!
if NOT EXIST !FolderPath!!name!.xml set flag=MISSING
if NOT EXIST !FolderPath!!name!.pdf set flag=MISSING
)
echo Flag: !flag!
pause
endlocal
You should reformat your code and keep in mind that the grama for batch file is critical. BTW, if you are trying to update the existing batch variable and read it later, you should enable localdelayedexpansion and use ! instead of %.
Keep it simple:
#echo off
pushd "E:\TestBat\Test" || exit /B 1
for %%F in ("*.pdf") do if not exist "%%~nF.xml" echo %%~nxF
for %%F in ("*.xml") do if not exist "%%~nF.pdf" echo %%~nxF
popd
This returns all files that appear orphaned, that is, where the file with the same name but the other extension (.pdf, .xml) is missing. To implement a variable FLAG to indicate there are missing files, simply append & set "FLAG=missing" to each for line and ensure FLAG is empty initially. Then you can check it later by simply using if defined FLAG.
Note: This does not cover the e-mail notification issue. Since I do not know the BLAT tool you mentioned, I have no clue how you want to transfer the listed files to it (command line arguments, temporary file, or STDIN stream?).
In case there is a huge number of files in the target directory, another approach might be better in terms of performance, provided that the number of file system accesses is reduced drastically (note that the above script accesses the file system within the for loop body by if exist, hence for every iterated file individually). So here is an attempt relying on a temporary file and the findstr command:
#echo off
pushd "E:\TestBat\Test" || exit /B 1
rem // Return all orphaned `.pdf` files:
call :SUB "*.pdf" "*.xml"
rem // Return all orphaned `.xml` files:
call :SUB "*.xml" "*.pdf"
popd
exit /B
:SUB val_pattern_orphaned val_pattern_missing
set "LIST=%TEMP%\%~n0_%RANDOM%.tmp"
> "%LIST%" (
rem // Retrieve list of files with one extension:
for %%F in ("%~2") do (
rem /* Replace the extension by the other one,
rem then write the list to a temporary file;
rem this constitutes a list of expected files: */
echo(%%~nF%~x1
)
)
rem /* Search actual list of files with the other extension
rem for occurrences of the list of expected files and
rem return each item that does not match: */
dir /B /A:-D "%~1" | findstr /L /I /X /V /G:"%LIST%"
rem // Clean up the temporary file:
del "%LIST%"
exit /B
To understand how it works, let us concentrate on the first sub-routine call call :SUB "*.pdf" "*.xml" using an example; let us assume the target directory contains the following files:
AlOnE.xml
ExtrA.pdf
sAmplE.pdf
sAmplE.xml
So in the for loop a list of .xml files is gathered:
AlOnE.xml
sAmplE.xml
This is written to a temporary file but with the extensions .xml replaced by .pdf:
AlOnE.pdf
sAmplE.pdf
The next step is to generate a list of actually existing .pdf files:
ExtrA.pdf
sAmplE.pdf
This is piped into a findstr command line, that searches this list for search strings that are gathered from the temporary file, returning non-matching lines only. In other words, findstr returns only those lines of the input list that do not occur in the temporary file:
ExtrA.pdf
To finally get also orphaned .xml files, the second sub-routine call is needed.
Since this script uses a temporary file containing a file list which is processed once by findstr to find any orphaned files per extension, the overall number of file system access operations is lower. The weakest part however is the for loop (containing string concatenation operations).

Put files automatically in folders

I have thousands of JPGs named like this "aaa0001.jpg, aaa0002.jpg, aaa0003.jpg,
bbb0001.jpg, bbb0002.jpg, bbb0003.jpg, ccc0001.jpg, ccc0002.jpg, ccc0003.jpg etc." in one folder.
I have created 26 folders like this aaa, bbb, ccc, ddd etc.
Is it possible to create a script that sets all the images in the appropriate folder?
Result "aaa0001.jpg, aaa0002.jpg, aaa0003.jpg" into folder "aaa",
"bbb0001.jpg, bbb0002.jpg, bbb0003.jpg" into folder "bbb" etc.
Thank you!
My system is windows XP prof SP3...
It would go like this in a Windows/dos batch file.
The statement %fp:~0,3% determines which part of the filename is used as a foldername. 0,3 means: from the first character and the next 3 chars.
so a file named aaa001-01.jpg will give a folder of aaa.
To have files named abc001_03.jpg go into folder 001 you change the statement to %fp:~3,3%
for %%a in (*.jpg) do call :copyfile %%a
goto :eof
:copyfile
set fp=%1
set folder=%fp:~0,3%
rem remove echo on the next line...
echo copy "%1" "%folder%"
rem or for moving: move /Y "%1" "%folder%"
goto :eof
Just define the base path to create the news directorys in the VAR $path
#echo off
setlocal EnableDelayedExpansion
:::The path where the new Directorys will bw created
set $path="c:\Image\"
for %%a in (*.jpg) do (set $file="%%a"
set $Dir="%$path%CSV!$file:~4,3!"
if not exist "!$dir!" md "!$dir!"
move "!$file!" "!$dir!")
echo Terminated

How to get attributes of a file using batch file

I am trying to make a batch file to delete malicious files from pendrive. I know that these malicious files uses hidden,read only and system attributes mainly to hide itself from users. Currently i am deleting these files using cmd by removing malicious files attributes then deleting it. Now I am thinking to make a small batch file which can be used to remove these files just by entering the drive letter.
I have found this code in a website to find attributes of a file. But after entering the name of the file the batch file just exits without showing any results.
#echo off
setlocal enabledelayedexpansion
color 0a
title Find Attributes in Files
:start
set /p atname=Name of the file:
if not exist %atname% (
cls
echo No file of that name exists!
echo.
echo Press any key to go back
pause>nul
goto start
)
for /f %%i in (%atname%) do set attribs=%%~ai
set attrib1=!attribs:~0,1!
set attrib2=!attribs:~1,1!
set attrib3=!attribs:~2,1!
set attrib4=!attribs:~3,1!
set attrib5=!attribs:~4,1!
set attrib6=!attribs:~5,1!
set attrib7=!attribs:~6,1!
set attrib8=!attribs:~7,1!
set attrib9=!attribs:~8,1!
cls
if %attrib1% equ d echo Directory
if %attrib2% equ r echo Read Only
if %attrib3% equ a echo Archived
if %attrib4% equ h echo Hidden
if %attrib5% equ s echo System File
if %attrib6% equ c echo Compressed File
if %attrib7% equ o echo Offline File
if %attrib8% equ t echo Temporary File
if %attrib9% equ l echo Reparse point
echo.
echo.
echo Press any key to go back
pause>nul
goto start
can you tell me why this batch file is exiting without showing any results. Or can you give any better batch script for getting attributes of a file.
EDIT
I was able to work the above code only for a single file. As my purpose of my batch file is to remove malicious files by entering the drive letter. How can i use it to find what kind of attributes files are using in a particular drive.
For example:
In cmd we can use this command to find the file attributes of a given drive
attrib *.*
Advance thanks for your help
I tried the bat file (without inspecting the details) and it seems to work fine for me. What I noticed is that it closes instantly if you don't enclose file path with quotation marks - e.g. "file". Example:
Name of the file: path\file.txt // this will close immediately
Name of the file: "path\file.txt" // now it will stay open and display the result
This hopefully solves your problem.
As far as your question in EDIT is concerned, a simple option is to iterate a list of files and execute the batch on each one.
batch1.bat: (%1 refers to the first command-line parameter)
#echo off
setlocal enabledelayedexpansion
echo %1
set atname=%1
for %%i in ("%atname%") do set attribs=%%~ai
set attrib1=!attribs:~0,1!
set attrib2=!attribs:~1,1!
set attrib3=!attribs:~2,1!
set attrib4=!attribs:~3,1!
set attrib5=!attribs:~4,1!
set attrib6=!attribs:~5,1!
set attrib7=!attribs:~6,1!
set attrib8=!attribs:~7,1!
set attrib9=!attribs:~8,1!
cls
if %attrib1% equ d echo Directory
if %attrib2% equ r echo Read Only
if %attrib3% equ a echo Archived
if %attrib4% equ h echo Hidden
if %attrib5% equ s echo System File
if %attrib6% equ c echo Compressed File
if %attrib7% equ o echo Offline File
if %attrib8% equ t echo Temporary File
if %attrib9% equ l echo Reparse point
echo.
echo.
Next, generate a list of all files within a given path (say 'folder' including all subfolders):
dir /s /b folder > ListOfFiles.txt
main.bat (read ListOfFiles.txt line-by-line and pass each line to batch1.bat as a command line parameter):
#echo off
for /f "tokens=*" %%l in (ListOfFiles.txt) do (batch1.bat %%l)
Then, from cmd:
main.bat >> output.txt
The last step generates an output file with complete results. Granted, this can be done in a more polished (and probably shorter) way, but that's one obvious direction you could take.
You're using a for /f loop here, which isn't necessary (and may yield undesired results if the filename contains spaces). Change this:
for /f %%i in (%atname%) do set attribs=%%~ai
into this:
for %%i in ("%atname%") do set attribs=%%~ai
This is dangerous code - but it'll delete read only, hidden and system files.
It should fail to run on c: drive but I haven't tested it. Note that some Windows installs are on drives other than c:
#echo off
echo "%cd%"|find /i "c:\" >nul || (
del *.??? /ar /s /f
del *.??? /ah /s
del *.??? /as /s
)

CMD delete files

Perhaps someone can be of help; I have several files with the following naming convention:
fooR1.txt, fooR2.txt, fooR3.txt, . . . , fooR1000.txt
I wish to delete all the files greater than R500. I have several folders and I know how to pass through each folder, but I am not sure how to capture and delete the files with replication 501 and greater. How can I do such?
How about simply:
ren foo500.txt foo499bis.txt
del fooR5??.txt fooR6??.txt fooR7??.txt fooR8??.txt fooR9??.txt fooR10??.txt
ren foo499bis.txt foo500.txt
Not elegant, but efficient.
This will delete all files fooR###.txt where ### is greater than 500.
#echo off
setlocal EnableDelayedExpansion
for %%f in (fooR*.txt) do (
set num=%%~f
set num=!num:~4,-4!
if !num! gtr 500 del /q "%%~f"
)
endlocal
Because your range is open, I've reversed your criteria: delete anything that is not in the range 1-499. Please be aware that this is not exactly equivalent to yours, for example it will also delete a file named fooR001.txt or fooR_something_else.txt
It's also pretty slow.
#echo off
for %%F in (fooR*.txt) do (
echo %%F | findstr /v /r "fooR[1-9]\.txt fooR[1-9][0-9]\.txt fooR[1-4][0-9][0-9]\.txt" >nul && echo del %%F
)
First line (for) enumerates files starting with fooR, then for each file findstr checks if it does not match pattern (/v option) and finally a command is executed if a check (ie does not match) is positive (&& means execute only if previous command was successfull).
Code above will just echo commands, not execute them, so you may safely run it to verify it actually behaves as it should. To actually run delete, just remove echo in front of it.
note: you could actually run this directly from command line in a form of:
#for %F in (fooR*.txt) do #echo %%F | findstr /v /r "fooR[1-9]\.txt fooR[1-9][0-9]\.txt fooR[1-4][0-9][0-9]\.txt" >nul && echo del %F
You would need to make a Batch script for this. Then in the Batch file you could write.
DEL "fooR500.txt"
To delete all files with a .txt ending you would just write:
DEL "*.txt"
That's all I know, but if you want to get it so it does files 500 and higher you would have
to create a variable in Batch that holds the value 500 using:
set Value = 500
and then have it delete file "fooR" + Index + ".txt" so to do that you would have to do:
set "FilePre = fooR"
set "FileW = %FilePre% %Value%"
set "Ex = .txt"
set "FileX = %FileW% %Ex%"
del FileX
Then you will have to make Value go up by one and repeat the process 500 times until it reaches 1000.

Print request upon new file in folder

I've got the following problem:
I need to make something that checks to see whether a file has been added to a specific folder, ifso this file needs to be printed. I heard Windows maybe has something similar built in?
*Program constantly checks whether a file has been added*
File has been added
File gets printed immediately
I have found solutions, but you need to pay for them.
UPDATE
"Code supplied by Vik"
:start
set SECONDS=60
SET FILENAME=*.jpg
IF EXIST %FILENAME% MSPAINT /p %FILENAME%
choice /C a /T %SECONDS% /D a
DEL /Q %FILENAME%
goto :start
"Edits: COPY *.JPG file to a different folder (E.G. ImageHistory)"
"Edits: DELETE local *.JPG file leaving the monitor folder empty"
Any tips or help are welcome!
This batch file will check if the file printme.jpg exists every 60 seconds. If it exists, it will use the built-in MSPAINT program to print it. Feel free to configure SECONDS and FILENAME to suit your environment.
:start
set SECONDS=60
SET FILENAME=printme.jpg
IF EXIST %FILENAME% MSPAINT /p %FILENAME%
choice /C a /T %SECONDS% /D a
goto :start
Additional mods you may want to make:
If you are using an older version of Windows like XP, you may not have the CHOICE command. In that case, use ping to simulate sleeping: PING 1.1.1.1 -n 1 -w 60000 >NUL
You can add a line to delete the file after it's printed: DEL /Q %FILENAME%
EDIT (Below): Added multi-file, move and delete capability
set SECONDS=20
set FILEFOLDER=C:\dropfolder
set TEMPFOLDER=%FILEFOLDER%\TEMPFOLDER
set FILEWILDCARD=*.jpg
if not exist "%FILEFOLDER%" ECHO %FILEFOLDER% NOT FOUND ... CTRL-C TO EXIT && PAUSE
if not exist "%TEMPFOLDER%" ECHO %TEMPFOLDER% NOT FOUND ... CTRL-C TO EXIT && PAUSE
:start
cd "%FILEFOLDER%"
dir /b "%FILEWILDCARD%" > filelist.txt
for %%A in (filelist.txt) do if not %%~zA==0 goto printfiles
choice /C a /T %SECONDS% /D a
goto :start
:printfiles
echo FILE(s) FOUND!
del /q "%TEMPFOLDER%\%FILEWILDCARD%"
move "%FILEWILDCARD%" "%TEMPFOLDER%"
cd "%TEMPFOLDER%"
for %%A in ("%FILEWILDCARD%") do MSPAINT /p "%%A"
goto :start
Run a VB.Net in Background and use a FileSystemWatcher to get events for each change in that folder. Upon receiving an event, check the file / action and print the file using whatever App that can print them. A Batch file will likely not work here.

Resources