I need to delete specific files from 28 folders on the same server.
e.g
C:/folder/DMP/app_x0
C:/folder/DMP/app_x1
C:/folder/DMP/app_x2
DeleteList.txt has a list of files names (with path).
C:/folder/DMP/app_x0/ABC1.txt
C:/folder/DMP/app_x0/ABC1.doc
The batch file needs to have a loop to go through each folder one by one and delete all files mentioned in a text file. Following worked ok for one folder only if I specify the full path before each file's names in DeleteList.txt file.
for /f "delims=" %%f in (DeleteList.txt) do del "%%f"
How to use above so that same code could run 28 times in batch file but each time replaces folder location path. DeleteList.txt will not change.
Any sample code/suggestion would help.
Thx.
One of these questions where we need to read between the lines.
Given we have on file of full filenames with the incorrect path separator, and a requirement to delete the files from 28 directories (but there's no list) then I conclude that since the required subdirectories shown are all subdirectories of C:\folder\DMP\ then the requirement actually is to delete all of the files that match the filenames in the file in all subdirectories of the parent directory of the full filename in the list.
So my suggestion would be
for /f "delims=" %%b in (DeleteList.txt) do del /s "%%~dpb..\%%~nxb"
Naturally, you should test this on a dummy tree before implementing it.
del /s deletes in the target directory and all subdirectories. The target subdirectory is the drive and path of %%b; its parent (..); the name and extension part of %%b.
I prefer to use metavariables that are not available as metavariable-modifiers.
To delete in subdirectories but not in the parent:
for /f "delims=" %%b in (DeleteList.txt) do FOR /d %%c IN ("%%~dpb..\*") DO del /s "%%c\%%~nxb">nul
This time, %%c is set to all subdirectorynames in turn, and the del/s applied to each subdirectory. The /s (...and subdirectories) probably isn't required. The >nul suppresses the deletion report if desired.
Not sure if the OP has need for this anymore, but you can use the following batch script to delete the specific files from multiple folders, starting from a parent folder.
#echo off
for /r "Drive:\path\to\parent_folder" %%d in (.) do (
del "%%~d\ABC1.txt"
del "%%~d\ABC1.doc"
)
The script will loop through the parent directory and its sub-folders, and delete only the specific files from the folders that they appear.
In the case of the post, the parent folder can be "C:\folder".
Related
Okay, I do not really know how to describe fully what I want and I feel bad for asking something so advanced. I do not know how to do anything other than move folders and delete files and folders using batch.
I am trying to make a batch file to delete certain Steam files and folders which are used to cache data. I could easily make this for myself and call it a day however I would like to share it and have it work for other people also. The problem is one of the cache folders is named with a unique Steam identifier. I will put what I have made so far below.
REM Makes a temporary folder.
mkdir %LocalAppData%\Temp\steam_cache
REM Deleted all none essential files in Steam's configuration folder.
move "%ProgramFiles(x86)%\Steam\config\config.vdf" %LocalAppData%\Temp\steam_cache
move "%ProgramFiles(x86)%\Steam\config\loginusers.vdf" %LocalAppData%\Temp\steam_cache
rmdir "%ProgramFiles(x86)%\Steam\config" /s /q
mkdir "%ProgramFiles(x86)%\Steam\config"
move %LocalAppData%\Temp\steam_cache\config.vdf "%ProgramFiles(x86)%\Steam\config"
move %LocalAppData%\Temp\steam_cache\loginusers.vdf "%ProgramFiles(x86)%\Steam\config"
REM Delete all none essential files in Steam's userdata folder.
I will put what the file structure goes like below.
%ProgramFiles(x86)%\Steam\userdata\256283931
As you can see the number at the end is completely random and I do not know how to open that directory without knowing the number first. There are sometimes multiple of these folders with random names if you login with multiple account and I would like the batch file to go into them one by one and delete certain folder inside of them.
I will put below the folders that I would like to delete that are inside of the random numbered folder below.
%ProgramFiles(x86)%\Steam\userdata\256283931\ugcmsgcache
Sorry if what I am asking it too much if so just ignore this post, thanks.
What you are looking for is the for /D loop, which enumerates directories:
rem // Enumerate all directories under `userdata`:
for /D %%I in ("%ProgramFiles(x86)%\Steam\userdata\*") do (
rem // Check if there is really a sub-directory called `ugcmsgcache`:
if exist "%%~I\ugcmsgcache\" (
rem // Do something with the full path, like echoing, for instance:
echo "%%~I\ugcmsgcache"
)
)
If you want to ensure that the name of the enumerated directory/-ies name consist(s) of decimal figures only, you could use dir and findstr, together with a for /F loop:
rem // Change into parent directory, because `dir /B` returns plain directory names:
cd /D "%ProgramFiles(x86)%\Steam\userdata"
rem // Enumerate all directories under `userdata`, whose names are pure numbers:
for /F "delims=" %%I in ('
dir /B /A:D "*" ^| findstr /I /X "[0123456789]*"
') do (
rem // Do something with the full path, like echoing, for instance:
echo "%%~fI\ugcmsgcache"
)
The cd command could also be replaced by pushd and popd.
The ~f modifier ensures that the full path is derived, related to the current working directory.
Note that the pipe (|) needs to be escaped here, because it is in the set of the for /F loop.
I have one directory with around 100 subdirectories, which include images. I then have a .txt list of images I need to delete from these folders.
Since there are a few thousands, I'm looking for a way to batch delete these using bat file.
But the problem is that my files are in subfolders and subfolders and also filenames include spaces.
Example:
MainFolder/Subfolder One/Image Sunshine.jpg<br>
MainFolder/Subfolder One/Image Cloudy.jpg
I've tried multiple options of del, also by putting all paths in txt file inside double quotes. But nothing deletes them.
Any ideas how to delete only the selected ones from all subfolders?
Renaming or deleting spaces is not an option, since I would have to reupload the remaining images back in the same form as current.
An easy way to do this is by using an FOR statement to read each line of the text document as a string.
For the removal of the files we can use the DEL command along with the /s switch to search all sub-directories.
/P - Prompts for confirmation before deleting each file.
/F - Force deleting of read-only files.
/S - Delete specified files from all subdirectories.
/Q - Quiet mode, do not ask if ok to delete on global wildcard
/A - Selects files to delete based on attributes
The following script will remove all file.extension's from the list.txt file from all sub-directories in the directory tree including the execution directory. This will also remove them if they have spaces in the name as "%%G" is quoted.
Batch File:
for /f "delims== tokens=1,2" %%G in (list.txt) do (del /s /q /f "%%G")
Command Prompt: (Be sure to CD to the main directory!)
for /f "delims== tokens=1,2" %G in (list.txt) do (del /s /q /f "%G")
First of all, similar questions have been answered in past but not exactly the one I have. In some other solutions, hiding folders/files and changing attributes were suggested and I do not want this, unless there is no simpler way available. Also, I have tried the solution suggested here (and couple of others): MS-DOS command to delete all files except one.
But did not work for my need due to two reasons:
This also deleted the file, I did not want to.
This did not delete the sub-folders but only the files.
So, I have folder c:/users/data and in there, I have 5 folders and 6 files I want to delete everything except one which is web.config and to do that I run the batch file like this:
#echo off
for %%j in (C:\Users\data\*) do if not %%j == Web.config del %%j
pause
But when I run the batch file, this deletes all the files including web.config and also, does not delete any of the sub-folders and if I use the /d switch then it only deletes folders not files. How can I delete both files and folders?
Here is the way I would do it:
pushd "C:\Users\data" || exit /B 1
for /D %%D in ("*") do (
rd /S /Q "%%~D"
)
for %%F in ("*") do (
if /I not "%%~nxF"=="web.config" del "%%~F"
)
popd
The basic code is taken from my answer to the question Deleting Folder Contents but not the folder but with the del command replaced by a second for loop that walks through all files and deletes only those not named web.config.
Note that this approach does not touch the original parent directory, neither does it touch the original file web.config. The great advantage of this fact is that no attributes are going to be lost (for instance, creation date and owner).
Explanation
change to root directory by pushd; in case of failure, skip the rest of the script;
iterate through all the immediate sub-folders of the root by a for /D loop and delete them recursively by rd /S with all their contents;
iterate through the files located in the root by a standard for loop; use the ~nx modifier of the loop variable to expand base name (n) and extension (x) of each file, compare it with the given file name (if) in a case-insensitive manner (/I) and delete the file by del only in case it does not match (not);
restore former working directory by popd finally;
The main problems in your code are:
that you compare more that the pure file name with the prefedined name, so there is not going to be found any match.
you needed to use case-insensitive comparison, because Windows does not care about the case of file names for searching.
you did not put quotation marks around the comparison expressions, so you are likely going to receive syntax error messages, depending on what special characters occur in the file names.
that you are using the del command only which just deletes files; to remove directories, you needed to use rd also.
I'm not sure where the web.config file is stored or if there is more than one, so ...
Only one web.config file
Just lock the file (redirect the file as input) and remove anything else
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
<"web.config" rmdir . /s /q
popd
)
The code will
(pushd) Change to the target folder (we need to be sure this will remove information only from the intended place) setting it as the current active directory and locking it (we can not remove the current active directory). If the command can change to the folder then
(rmdir) Redirect the web.config as input to the rmdir command. This will lock the file so it can not be deleted until the command ends. The rmdir . /s /q remove anything not locked inside (and below) the current active directory
(popd) Cancel the pushd command restoring the previous active directory
Several web.config files in multiple folders
Following the approach (copy, clean, restore) pointed by #Dominique
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
for %%t in ("%temp%\%~n0_%random%%random%%random%.tmp") do (
robocopy . "%%~ft" web.config /s
robocopy "%%~ft" . /mir
rmdir "%%~ft" /s /q
)
popd
)
The code will
(pushd) Change to the target folder (we need to be sure this will remove information only from the intended place). If the command can change to the folder then
(for) Prepare a reference (a random name) to a temporary folder to use
(robocopy) Copy only the web.config files (and their folder hierarchy) from the source folder to the temporary folder
(robocopy) Mirror the temporary folder to the source folder. This will remove any file/folder not included in the temporary copy
(rmdir) Remove the temporary folder
(popd) Cancel the pushd command restoring the previous active directory
Once the web.config files are saved, as the files in the source will match those in the temporay folder, they will not be copied back with the second robocopy call, but any file/folder in source that is not present in the temporary folder will be removed to mirror the structure in the temporary folder.
I also managed to do it, very similar to #aschipfl
For /D %%k in (C:\Users\data) do (For /d %%m in ("%%k\*") do rmdir /s /q "%%m"
For %%m in ("%%k\*") do if not %%m == %%k\Web.config del /q "%%m")
I am new to scripting, can some please assist me,
I have batch file that
Looks at the first 8 characters in the file name, creates and
moves those files to new folder with first 8 characters as folder
name.
Then looks at folder created in step 1 for next four series
of character (9,10,11,12)and create and move to another subfolder
with next 4 characters as folder name.
Then looks at folder created in step 2, for extension of every file and create and move
to a new folder with extension as folder name.
For example, I have files that look like this
ABCEFGHI0703xyz.pdf
STUVWXYZ0805xyz.pptx
Move to folder
ABCEFGHI\0703\PDF
STUVWXYZ\0805\PPTX
Keeping in mind first 8 characters are random, next 4 character are year and month, and 9 types of extensions.
I am using this batch script to create these folders:-
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\sourcedir"
SET "destdir=C:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*" '
) DO (
SET name=%%~na
SET ext=%%~xa
SET name=!name:~0,8!\!name:~8,4!\!ext:~1!
MD "!name!" 2>nul
MOVE "%sourcedir%\%%a" "!name!\" >nul
)
GOTO :EOF
Now I would like to add a WINRAR command to archive just the extension folders created in step 3, I am using this command to create the archives.
C:\ ABCEFGHI\0703\PDF>WINRAR A PDF C:\ ABCEFGHI\0703\PDF
Is it possible to add this command to the script?
Ok first you need to have rar.exe in a folder in %PATH%,
i'd suggest you put a link in your Windows\System32 folder like so:
mklink C:\Windows\System32\rar.exe "C:\Program Files\WinRAR\rar.exe"
then you can get to work.
As you already suggested, first create the desired directory tree and then just add the required files to your archive like so:
rar.exe a %ARCHIVE_NAME% MainFolder\*.pdf
rar.exe a %ARCHIVE_NAME% MainFolder\FolderA\*
rar.exe a %ARCHIVE_NAME% MainFolder\FolderB\*
Whereas %ARCHIVE_NAME% is the file name of your new target archive (such as foo.rar)
This will every *.pdf file in 'MainFolder' and everything in 'FolderA' and 'FolderB'. The directory tree will be preserved.
Also, you may want to check whether %ARCHIVE_NAME% already exists, since rar will just add the specified files to an existing archive (possibly overriding them)
Hope this clarifies some things for you.
Edit: doing this recursivly for unknown root directory
set ARCHIVE_NAME=%CD%\pdf_archive.rar
for /r %CD% %%d in ('PDF') do (
if exist "%%d" (
echo Archiving files in: %%d
rar a "%ARCHIVE_NAME% "%%d"\*
)
)
Now this will go into every subdirectory recursivly (starting from your current directory)
Then iw will look for folders called 'PDF' and if they exist it will archive every file in that folder to %ARCHIVE_NAME%
In a folder, I have some folders. I want to compress all the folders separately to the foldername.rar and delete the original files. I want to perform this function in batch.
I tried the ones given in other answers but they only compress the files if present, or do nothing. Here , I have to compress only folders to their respective archive. Please help
WinRAR includes two command-line tools, rar.exe and unrar.exe, where rar.exe compresses and unrar.exe uncompresses files.
Both are located in the “C:\Program Files\WinRAR” folder in the installable version.
Assuming, if there are multiple folders under D:\test and you want each folder to get its own .rar file , in the parent folder, from a batch file, this works for you:
#echo off
setlocal
set zip="C:\Program Files\WinRAR\rar.exe" a -r -u -df
dir D:\test /ad /s /b > D:\test\folders.txt
for /f %%f in (D:\test\folders.txt) do if not exist D:\test\%%~nf.rar %zip% D:\test \%%~nf.rar %%f
endlocal
exit
Explanation....
It'll create .rar files of all the folders/subfolders under parent folder D:\test in the same parent folder.
Then, it'll delete all the original folders/subfolders under parent folder D:\test and thus you'll be left only with the archives at the same place.
“a” command adds to the archive
“-r” switch recurses subfolders
“-u” switch. Equivalent to the “u” command when combined with the “a” command. Adds new files and updates older versions of the files already in the archive
“-df” switch deletes files after they are moved to the archive
Maybe something like this, change C:\testfolder\ to you liking.
In my example I had 3 folders (with random files and subfolders inside em): one, two and three
#echo off
cd "C:\testfolder\"
for /d %%G in ("*") do (
"%programfiles%\WinRAR\Rar.exe" a -r %%G.rar %%G
rd /s /q %%G
)