Will this be possible with a batch file? - batch-file

Before I start posting code I am wondering if this is even feasible.
I have a directory of folders I need to move to a new directory.
But I only need to move the folders that contain only 2 files in them.
The rest of the folders have more than 2 files in them, but they need to stay.
So would this be feasible with a batch file?

This was interesting so I took a stab at it:
#echo off
set "dir=C:\Your\Current\Directory"
set "ndir=C:\Your\New\Directory"
setlocal enabledelayedexpansion
for /d %%A in (%dir%\*) do (
pushd "%%A"
for /f %%B in ('dir /a-d-s-h /b ^| find /v /c ""') do (
set cnt=%%B
if "!cnt!" == "2" (if not exist "%ndir%\%%~nA" robocopy "%%A" "%ndir%\%%~nA" /e)
)
)
pause
I kept running into issues so I modified a few things to make it do what I wanted; there're likely more elegant ways to go about it, but this worked ¯\_(ツ)_/¯. First thing is setting variables for your current directory (dir) and your new directory (ndir) to make it a little easier to digest later on; we also need to enable delayed expansion since the value of our counting variable (cnt) will change between loop iterations. The first FOR loop is /d, which will loop through folders - we set each of those folders as parameter %%A and use that to change our directory (using pushd) prior to running our nested commands.
The second FOR loop is /f, which will loop through command results - the commands in this case being dir and find. For dir we are specifying /a to show all files that -d aren't folders, -s system files, or -h hidden files, and we display that output in /b bare format. Using the output from dir, we run find and specify to /v display all non-empty lines and then /c count the number - which becomes parameter %%B.
Finally, we set %%B as our counting variable (cnt) - if !cnt! is equal to 2, we see if the folder already exists in the new directory, and if it does not we robocopy it over. The move command was giving me some trouble because the folder would be locked by the loop, so if you want you could also throw in a DEL command to delete the original folder.
Let me know if that helps! Hopefully your research was going well anyway.
References: Counting Files, FOR Looping, pushd, DIR, FIND, robocopy

Related

how to zip all files individually in all subfolders and remove original file after

what im looking for is a .bat file code to zip files individually in all subfolders in the current folder and then delete the of files after, to exclude already zipped/compressed files, what i dont want is folders to be zipped and i want the files to keep there name when zipped
i have a bunch of folders/files and the only code i found
#ECHO OFF
FOR %%i IN (*.*) DO (
ECHO "%%i" | FIND /I "batch zip files.bat" 1>NUL) || (
"c:\Program Files\7-Zip\7z.exe" a -tzip "%%~ni.zip" "%%i"
if %ERRORLEVEL% == 0 del "%%i"
)
)
zips all files in the current directory and doesnt touch subfolders
i'd appreciate it if anyone can do this for me as i can save a ton of space with all files zipped
The first issue you have with your provided code is that your For loop is only parsing files in the current directory, there is no recursion into subdirectories. To parse files within the subdirectories, I'd advise that you use a For /F loop, with the Dir command using its /B and /S options. I would also advise that you include the attribute option, /A, which will include every item, then omit those which you're not interested in. For instance, it's unlikely that you want to zip the directories, hidden files, reparse points, or system files. You can do that by excluding those attributes, /A:-D-H-L-S. To learn more about the For command, and the Dir command, open a Command Prompt window, type for /?, and press the ENTER key. You can then do the same for the Dir command, i.e for /?. As you have not defined a working directory at the start of your script, it will run against every file and directory in whatever is current at the time you run it. Because your code has a line excluding a file named batch zip files.bat, I'm going to assume that is the name of your running script, and that your intention is to therefore run the script against everything in the tree rooted from the same location as the batch file itself. To ensure that is always the case, for safety, I've defined that directory as the current directory from the outset, using the CD command, CD /D "%~dp0". %0 is a special batch file argument reference to itself, to learn more about this please take a look at the output from both call /?. You can also learn about the CD command entering cd /?, in a Command Prompt window too. To also omit your batch file, as you don't want it to be zipped and deleted, I've piped the results from the Dir command through FindStr, printing only items which do not exactly match the case insensitive literal string %~f0 (expanding to the full path of the batch file itself). Additionally, I've piped those results through another findstr.exe command to omit any files already carrying a .zip extension, as there's no point in zipping files which already zip files. (Please note however, that for more robust code, you should really check that those are zip archives and not just files carrying a misleading extension). The results from those commands are then passed one by one to the Do portion which includes your 7z.exe command. I've assumed at this stage, that your intention was to save the zipped archives to the same location as the originating files. To do that I've used variable expansion on %%G to stipulate its directory, path, and name, %%~dpnG, (see the usage information under for /? to recap). Upon successful completion of the archiving process, the original file will be deleted, to do that I appended the -sdel option to your original command string. Please be aware that you may want to include additional options, should you wish to update existing zip files etc. (use "%ProgramFiles%\7-Zip\7z.exe" -? in a Command Prompt window to see them). As I've not mentioned it previously, at the beginning of the script, I made sure that extensions were enabled. Whilst it is the default option, it's safer to be sure, as variable expansion and the commands CD, and For can be affected, if they're not.
Here's the code as explained above:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /I /L /V /X "%~f0" ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnG.zip" "%%G" -sdel
Looking at your question, which has changed from what you'd asked initially, you appear to not be interested in the files of the batch file directory any more, "zip files individually in all subfolders in the current folder". For that reason, I've provided the following alternative, methodology.
The difference is that I first of all use a For loop to include only directories in the current working location, /A:D-H-L-S, before running the same method used in my previous example, but with one difference. As we're now no longer zipping files in the current working directory, we can remove the findstr.exe command filtering out the running batch file:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:D-H-L-S /B 2^> NUL'
) Do For /F "EOL=? Delims=" %%H In ('Dir "%%G" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnH.zip" "%%H" -sdel
Please be aware, that my answers above are to essentially correct your code attempt, and not a personal recommendation for speed, or in performing the task laid out in your question. Additionally, I have no idea what will happen if any of those files are in use/locked, and have made no attempt at checking for such scenarios.

Use multiple wildcards in a path in batch file

First of all, there are similar questions on Stack OverFlow like:
Windows - Batch file ignoring multiple wildcards
How to specify multiple wildcards in a folder directory in CMD
However, my use-case is a bit specific (or let's say: I couldn't manage to solve my problem using the lessons learned from the previous forum entries - mind that I am a pure beginner with Batch files).
What I want to do is to grab a file from a certain path, which includes a few subfolders (which change their names) - and copy it to another path which has similar folder structure.
I am currently stuck at the point, that I don't know how to set multiple wildcards in the source path, as it consists of a few things changing. Example:
File in Source:
C:\20170621_Update2017SR1\Polarion_update\_backup-20170627-1602.05\polarion\plugins\com.polarion.alm.tracker_3.17.0\configuration\MyPolarion\page.xml
Target Directory:
C:\Polarion\polarion\plugins\com.polarion.alm.tracker_3.18.2\configuration\My Polarion
Basically only the parts with numbers can change, so I was trying the following:
for /D %%a in ("C:\Polarion\polarion\plugins\com.polarion.alm.tracker*") do set "com.polarion.alm.tracker=%%a"
for /D %%b in ("C:\*_Update*\Polarion_update\_backup-*\polarion\plugins\com.polarion.alm.tracker*") do set "folder=%%b"
echo %com.polarion.alm.tracker%
echo %folder%
set source="%folder%\configuration\MyPolarion\page.xml"
set destination="%com.polarion.alm.tracker%\configuration\My Polarion"
xcopy /s /Y %source% %destination%
I am pretty sure line 2 of my Code contains mistakes - because I don't know if I can set multiple wildcards like this.
The console gives me for line 2:
Echo is on
I don't understand what it means and what should I do.
As I already mentioned in a comment, wildcards can only be used in the very last element of a path (independent on whether this is a file or directory). That is why your command line containing C:\*_Update*\Polarion_update\... fails. However, you can resolve every directory level with wildcards individually, like this:
set "folder="
for /D %%b in ("C:\*_Update*") do (
for /D %%c in ("%%~b\Polarion_update\_backup-*") do (
for /D %%d in ("%%~c\polarion\plugins\com.polarion.alm.tracker*") do (
set "folder=%%~d"
)
)
)
echo "%folder%"
If there are more than one matching directories on any levels, replace set "folder=%%~d" by echo "%%~d" to view them all.

batch file : overwrite one file to several existing files

I am trying to make simple security program for my company.
We usually make a lot of doc or ppt(x) files and
for some reason, we need to make them disable as soon as possible.
So we usually deleted the all of files but It took so long.
So I thought I can do that by overwritting the files.
If I have a empty doc or ppt files then overwite all of doc, ppt files in working drive each, then it will be faster and much safer than just deleting.
So I tried to use xcopy
Assuming empty.doc is just empty doc file and
xcopy /s /y c:\users\mycom\empty.doc c:\*.doc
But it said cannot perform cyclic copy
I need you guys help
and I am glad to hear suggestion.
Thanks.
This is an old, old batch file that I employed for such an endeavour:
:: dispose.bat
#echo off
:: Check parameter(s), stripping quotes
set yp1=%1
set ydf=
:insistp1
if defined yp1 set yp1=%yp1:"=%
if not defined yp1 for %%i in (echo goto) do %%i error - filename required
if not exist "%yp1%" for %%i in (echo goto) do %%i error - file not found
for %%i in ("%yp1%") do (set yfr=%%i&call :zapit %%~di) 2>nul
:error
:: Clean up variables used
if defined ydf echo Warning! dispose failed!!
for %%i in (yp1 yfr yrn ydf) do set %%i=
goto :eof
:zapit
set yfr=%yfr:"=%
IF /i %1 == u: DEL "%yfr%" &goto :eof
if not exist %1\delete\. md %1\delete
(set yrn=)
:rndloop
set yrn=%yrn%%random%
if exist %1\delete\%yrn% goto rndloop
if not exist "%yfr%" set ydf=Y&goto :eof
move "%yfr%" %1\delete\%yrn%>nul
goto :eof
:: dispose.bat ends
Noting that u: is a RAMDRIVE on my system, hence mere deletion is all that is required.
The purpose is not to actually delete the files, but to move them to a directory named ?:\delete and provide them with a random name in that directory.
Since the file is simply MOVEd it is quite fast, which addresses your time consideration.
An issue for me is the idea of copying a file over all of the files you target. If the file that you copy is shorter than the other files, some data wilstill be available to be recovered. Regardless, it will alwats be slower than simply deleting the files (which you say you are currently doing.)
This scheme simply accumulates the files-to-be-deleted in a known directory on the same drive (so they will simply be moved, not copied.)
Once they are in your \delete directory, you can let a utility like ccleaner or recuva loose on that single directory in the background and it will overwrite the files a specified number of times.
Here's a simpler method. Be careful.
At the command line:
for /r c:\ %A in (*.doc? *.ppt?) do echo. > %A
In a batch file:
for /r c:\ %%A in (*.doc? *.ppt?) do echo. > %%A
EDIT:
To replace with a file, see the example below. Replace the example's d:\path\file.ext with your intended file. Note that the previous option will work much faster with a similar result.
At the command line:
for /r c:\ %A in (*.doc? *.ppt?) do copy d:\path\file.ext > %A
In a batch file:
for /r c:\ %%A in (*.doc? *.ppt?) do copy d:\path\file.ext > %%A
Either way, as noted in Magoo's answer, larger files will still have recoverable data on the drive. You stated in a comment:
But if I overwrite the original files, then they cannot guess what it
was unless they got bak files
This isn't accurate. Forensic tools can retrieve the partial data that wasn't overwritten with new content.

Batch move files in folders to newly created folders

I want to move all files in some folders to a newly created folder in that same folder. For easier understanding, see the example below (the input is shown left, output is shown right):
C:\1\A\file1.tif C:\1\A\Named\file1.tif
file2.tif file2.tif
file3.tif ==> file3.tif
C:\1\B\file1.tif C:\1\B\Named\file1.tif
file2.tif file2.tif
file3.tif file3.tif
In the example above, I have only shown the first three files in every folder, but the total number may vary (usually there are 1000 files per folder). Also, I have only shown two folders (A and B), but the total number of folders may vary as well (usually about 10 folders). Finally, I have only shown the folder '1', but the number of these kind of folders may also vary (usually '1' through '10'). So I was looking to a script that could do these actions independent of the number of files or folders, and independent of the names of the folders/files (I chose '1', 'A' and 'file1.tif' only as examples).
The idea is that, now, I have to manually create empty folders (called 'Named' in the example above) in each folder ('A' and 'B' in the example above) where the files are. Then I have to manually move all the files into that newly created folder 'Named'. I have to do this for all folders (about 100). I can do this entire process manually if I had to do it only once, but the thing is that I have to do this process many times :-). So automating this would save a lot of time.
Does anyone know a script that can do this? Thanks a lot!
tested a little, this might work, in a command file
make a cmd file with these lines
for /r %%a in (*.*) do call :singlecopy %%a
goto :eof
:singlecopy
set src=%~p1
set dst=%~p1NAMED
set file=%~n1%~x1
rem replace NAMED in src with nothing
set srctst=%src:NAMED=%
rem if src and srctst are still the same, copy
if %srctst%==%src% robocopy %src% %dst% %file% /move /create
goto :eof
After thorough testing, this works great. However, as it is a lot of files, you may want to set up a little test environment, like in your example, to use this on first, before you use it on your actual data.
setlocal enabledelayedexpansion
cd C:\rootfolder
for /f "tokens=*" %%a in ('dir /s /b /a:d') do (
attrib "%%a\*.*" | find "File not found"
if !errorlevel!==1 (
if not exist "%%a\Named" md "%%a\Named"
xcopy "%%a\*.*" "%%a\Named"
del "%%a\*.*" /f /q
)
)

How to remove all folders of name x within a directory using cmd/batch file

I have a folder named x with a number of subfolders and files. I want to delete a folder named y that is present in x and all of it's subfolders. The said folder that has to be deleted may or may not contain any files. I believe i can do this using cmd or some kind of batch file but i am a command line new bi and can really use some help.
A simple thing would be to rd the folder's name, which works but i believe there are better ways than removing each folder individually.. like some loop that goes through all the folders.
Thanks
EDIT: Just to clarify, i have y (the folder that needs to be deleted) inside of x, and it can be in any of x's subfolders and at any level of depth. Also i am looking at answers and it may take some time for me to accept any answer. Please bear with me :)
Here is another solution for this commented to describe each part of the script:
#Echo OFF
REM Important that Delayed Expansion is Enabled
setlocal enabledelayedexpansion
REM This sets what folder the batch is looking for and the root in which it starts the search:
set /p foldername=Please enter the foldername you want to delete:
set /p root=Please enter the root directory (ex: C:\TestFolder)
REM Checks each directory in the given root
FOR /R %root% %%A IN (.) DO (
if '%%A'=='' goto end
REM Correctly parses info for executing the loop and RM functions
set dir="%%A"
set dir=!dir:.=!
set directory=%%A
set directory=!directory::=!
set directory=!directory:\=;!
REM Checks each directory
for /f "tokens=* delims=;" %%P in ("!directory!") do call :loop %%P
)
REM After each directory is checked the batch will allow you to see folders deleted.
:end
pause
endlocal
exit
REM This loop checks each folder inside the directory for the specified folder name. This allows you to check multiple nested directories.
:loop
if '%1'=='' goto endloop
if '%1'=='%foldername%' (
rd /S /Q !dir!
echo !dir! was deleted.
)
SHIFT
goto :loop
:endloop
You can take the /p out from in front of the initial variables and just enter their values after the = if you don't want to be prompted:
set foldername=
set root=
You can also remove the echo in the loop portion and the pause in the end portion for the batch to run silently.
It might be a little more complicated, but the code can be applied to a lot of other uses.
I tested it looking for multiple instances of the same foldername qwerty in C:\Test:
C:\Test\qwerty
C:\Test\qwerty\subfolder
C:\Test\test\qwerty
C:\Test\test\test\qwerty
and all that was left was:
C:\Test\
C:\Test\test\
C:\Test\test\test\
FOR /D /R %%X IN (fileprefix*) DO RD /S /Q "%%X"
Take care of using that...
for RD command:
/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
the FOR command is used to loop through a list of files or variables, the options are very easy to memorize, Directory only Recursively.
A problem common to this type of topics is that if there are instances of the target folder at several levels, most methods cause an error because when an high level folder is deleted, all folders below it disappear. For example:
C:\X\Y\subfolder
C:\X\Y\subfolder\one\Y
C:\X\Y\subfolder\two\Y
C:\X\Y\subfolder\three\Y
C:\X\test
C:\X\test\test
Previous example generate a list of 4 folders named Y that will be deleted, but after the first one is deleted the three remaining names no longer exist, causing an error message when they are tried to delete. I understand this is a possibility in your case.
To solve this problem the folders must be deleted in bottom-up order, that is, the innermost folder must be deleted first and the top level folder must be deleted last. The way to achieve this is via a recursive subroutine:
#echo off
rem Enter into top level folder, process it and go back to original folder
pushd x
call :processFolder
popd
goto :EOF
:processFolder
rem For each folder in this level
for /D %%a in (*) do (
rem Enter into it, process it and go back to original
cd %%a
call :processFolder
cd ..
rem If is the target folder, delete it
if /I "%%a" == "y" (
rd /S /Q "%%a"
)
)
exit /B
Although in this particular case the problems caused by other methods are just multiple error messages, there are other cases when this processing order is fundamental.
Make .bat with following:
del /q "C:\Users\XXX\AppData\Local\Temp\*"
FOR /D %%p IN ("C:\Users\XXX\AppData\Local\Temp\*.*") DO rmdir "%%p" /s /q

Resources