Batch copying certain files within a folder - batch-file

I am trying to find specific files within a folder and its sub-folders and copy them to a new folder. I used to use this batch file for this purpose but now I get this error :
The system cannot find the file specified.
Here's the batch-file content:
pushd "\\internal.company.com\path\"
md myfile
FOR /R "\\internal.company.com\path\" %%G in (prefix_myfile*) do copy %%G "\\internal.company.com\path\myfile"
Any input is appreciated.
UPDATE
I tried printing %%G like this:
FOR /R "\\internal.company.com\path\" %%G in (prefix_myfile*) do echo %%G
and it works well. The problem arises with copy command which cannot read %%G as an argument.

I'd change to
... copy "%%G" ...
which would cater for spaces in %%G.
Perhaps you should determine whether the problem is with the for/r or %%G. If you simply display %%G with an echo %%G command, then you may see some problem. If it still won't run, then the for /r is the problem.
Since you are pushding to the appropriate directory, there is no need to specify the target directory in the for/r. It can be omitted or replaced by .
or perhaps echo %cd% directly after the pushd to show whether the pushd is the cause of the problem.

I realized that this would work for me (executed in cmd). However, it is plausible because I don't have any *.txt file in the main directory. Not the best solution but a workaround.
pushd "\\internal.company.com\path\"
rem first copy the desired files (text files) to the main-folder
for /f "tokens=*" %f in ('dir /a:-D /s /b myfile*') do copy "%f"
rem then make a new-folder and move them to there
md myfile
move *.txt "\\internal.company.com\path\myfile"
Note: if you want to execute this as a batch file, you need to use %%f instead of %f.
This will copy the files into main folder and then moves them into the desired sub-folder.

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.

Batch how to move hidden directories?

I am using the following script lines in a batch script (.bat) to copy the contents of a directory (foo) to another (bar):
move "C:\foo\*.*" "C:\bar\"
for /d %%a in ("C:\foo\*") do move "%%~fa" "C:\bar\"
The first line moves files and the second lines moves folders. However, these aren't moving the hidden directories. .git is a common example. I tried for /d %%a in ("C:\foo\.*") do move "%%~fa" "C:\bar\" with no success.
How can I move my hidden directories along with the rest of my files and directories?
EDIT: The following solution is very close to doing what is required, but fails because the "move" command can't find the hidden folder (tried the same on a .folder that wasn't hidden and it worked):
for /f "tokens=*" %%G in ('dir /b /a:hd "C:\foo\*"') do move "C:\foo\%%G" "C:\bar\"
For what you are trying to do, you can first use the attrib command before moving things to remove hidden attributes from files. You can use this to accomplish your goal:
attrib -h "C:\Program Files\Git\usr\tmp\*.*"
move "C:\Program Files\Git\usr\tmp\*.*" "C:\Program Files\Git\usr\bin\"
To do this with other things, you can do this:
attrib -h "<SourceParentFolder>\*.*"
move <source> <destination>
NOTES: You should note #Mark's comment. Using C:\file\path\folder\* is not correct. You should use C:\file\path\folder\*.*. For more information view #Mark's comment
For more information on attrib use attrib /? or check this
A file or directory name beginning with . does not mean that it is hidden.
Anyway, for/for /D iterates over non-hidden files/directories. However, dir allows to return hidden items as well when using its /A option, which can be made use of by using for /F:
rem // Change into source directory:
pushd "C:\Program Files\Git\usr\tmp" && (
rem // Iterate over all directories, even hidden and system ones:
for /F "delims= eol=|" %%I in ('dir /B /A:D-S-L ".*"') do (
rem // Actually move the directory:
move "%%I" "C:\Program Files\Git\usr\bin\"
)
rem // Return from source directory:
popd
)
After some extra research, I found that robocopy seems to be included by default in Windows 10 distributions and robocopy /MOVE allows moving all the needed files and folders in a single line, such as:
robocopy "C:\foo" "C:\bar" /E /MOVE
Additional logging options can be added to reduce the output to the command line.

7zip creating empty archives with batch file

I want to zip everything in a folder, EVERYTHING, but into individually named archives. For some reason every solution on the internet only zips folders, or fails to work at all.
Currently, I have
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\"
Which I interpret to mean
for = initiate a loop
/d = I don't know what this means
%%X = I don't know what this means
in = not sure, I think it means current directory
(*) = I don't know what this means
do = execute the next thing in "..."
"C:\Program Files\7-Zip\7z.exe" = the thing I want done.
a = add to archive
-m9 = max compression
"%%X.zip" = make it a zip file, though I still don't know what %%X is.
"%%X\" = even if I knew what "%%X\" meant I don't know why it's here.
I have figured out replacing %%X gives the archive a name, so it seems to copy the name of the thing being targeted.
So if I guess, I think /d is "target folders" and %%X is the name.
So
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\"
Says in English as I understand it: for every folder name in the current directory, use 7z to max compress it into a zip of the same name... except I don't know what to replace /d with to make it target files instead of folders. And targeting specific extensions would be even better.
I tried googling what does "/d in cmd mean," "what does %%X mean", etc. I don't seem to be getting correct results in the search, I think I'm being too vague for google.
UPDATE:
for %%i in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%i.zip" "%%i\*.*"
seems to make a zip file NAMED each item in the folder, but does not actually add any files to them. I tried adding /f, but it didn't work at all when I did that.
Additionally, the first time I posted this it was closed as a duplicate of Batch script loop which has almost nothing to do with my problem. Yes, I have a loop, yes that addresses batch loops, but no, it does not come close to solving my problem since my problem isn't with the loop itself., or if it does I have absolutely no idea why or how. So please, explain it to me. I did see the section where it says %%X is the variable, but that just means I suppose X could be anything I want it to be, and since in my update I indicated a secondary issue, I think the problem I'm having is with 7z and not the bat file.
The for command can be very confusing at first, however there is many videos and sites that show examples of how to use it.
To start with try for /? to see the built in help information.
The below code should be what you are after if i understand your requirements correctly.. if not then this should help you understand the principles and adjust for your needs.
for /F "tokens=*" %%a in ('DIR /A-D /B /ON "C:\Test Folder\"') do (
echo Processing File: C:\Test Folder\%%a
"C:\Program Files\7-Zip\7z.exe" a -mx1 -tzip "C:\Test Folder\%%a.zip" "C:\Test Folder\%%a"
echo.
)
pause
Now lets go through it line by line...
for /F "tokens=*" %%a in ('DIR /A-D /B /ON "C:\Test Folder\"') do (
/F Tells it to work with files instead of directories(/D)
in (' ') Contains the command that finds the filenames. Note the ' marks at each end of the command...they are important.
%%a Represents each value of a filename that the in() command passes it.
do ( ) What it should do with each %%a value it receives.
Now we get to the command that is finding the filenames and passing to the do () section as %%a
('DIR /A-D /B /ON "C:\Test Folder\"')
You can find more info on the this by running dir /?
/A-D Tells it to ignore Directories... only list files.
/B Output just the file names and not anything else like sizes or it will confuse the for command.
/ON Feed the filenames to the do() command in alphabetical order
"C:\Test Folder\" The folder that contains all the files we want to list/perform actions on. Make sure you include the trailing slash. Also use the "" marks or it wont work if a folder has a space in its name.
Write(echo) to the screen a message showing which file it is about to do.
echo Processing File: C:\Test Folder\%%a
You can find more information on how to use the 7zip command line functions at https://sevenzip.osdn.jp/chm/cmdline/syntax.htm
"C:\Program Files\7-Zip\7z.exe" a -mx1 -tzip "C:\Test Folder\%%a.zip" "C:\Test Folder\%%a"
"C:\Program Files\7-Zip\7z.exe" Run this program.... and pass it the following information (arguments/switches)
a Add files rather than extract, etc.
-mx1 Use the fastest compression method...but less space efficient.
-tzip Use the ZIP compression format
"C:\Test Folder\%%a.zip" Save the new "zip" file as this. (%%a will be replaced with the name of the current file... aka ChuckNorris.mpg which would end up as ChuckNorris.mpg.zip)
"C:\Test Folder\%%a" This is the actual file you want to zip.

Recursively append folder name to the files in Windows batch file

I would like to append my folder name to all the available .txt files inside a subfolder. Below is the file/directory structure. I need to achieve this in Windows BATCH script.
C:\Source\Source1\1\a.txt C:\Source\Source1\1\b.txt
C:\Source\Source1\2\a.txt C:\Source\Source1\2\b.txt
C:\Source\Source2\3\a.txt C:\Source\Source2\3\b.txt
The above files should be renamed like below:
C:\Source\Source1\1\1_a.txt C:\Source\Source1\1\1_b.txt
C:\Source\Source1\2\2_a.txt C:\Source\Source1\2\2_b.txt
C:\Source\Source2\3\3_a.txt C:\Source\Source2\3\3_b.txt
Similary, I have Source1...Source30 and under each source directory, I will have multiple folders with different numbers. I need to rename all the files under these directories and append the number(directory name) to the file name.
So far below is what I wrote:
for %%* in (.) do set CurrDirName=%%~nx*
echo %CurrDirName%
for /r %%x in (*.txt) do ren "%%x" "%CurrDirName%_%%x"
With this, I am able to achieve it in a single directory. I couldn't make it recursive. Could you guys please help me with this.
#echo OFF
SETLOCAL EnableExtensions
for /F "delims=" %%G in ('dir /B /S "C:\Source\*.txt"') do (
for %%g in ("%%~dpG.") do ECHO rename "%%~fG" "%%~nxg_%%~nxG"
)
pause
where the FOR loops are:
outer %%G loop creates a static list of .txt files (recursively), and
inner %%g loop gets the parent folder of every particular file.
The rename command is merely displayed using ECHO for debugging purposes. To make it operational, remove word ECHO (no sooner than debugged).
Moreover, I'd consider checking whether a particular file is already renamed…

Find any file in directory/subdirectory and copy to new directory

I have a directory with a number of folders that each include sub-folders. I want to run a batch that searches those folders for the existence of a specific sub-folder called "failed". If there is a file present in this sub-folder, I want it to then move that file to another defined folder.
I've tried to look up usage of "if exist" commands but can't seem to find anything that directly suits my needs.
The names and types of the files to be moved are random, which is why I believed the "if exist" to be the most utile.
Any suggestion?
Read help for paying attention to the /r and /d options and then try this one-liner in the command line
for /d /r %a in (failed) do #echo %a
you will see that this loop iterates over all the directory structure and appends failed to the directory name
then add a check for the actual existence of the directory
if exist %a\nul #echo %a
then add a second loop to iterate over all of the contents of the found failed directory
for %b in (%a\*) do #echo %b
then replace the echo with the required move command
move %b %destination%\%~nxb
and there you go, with a simple single line
for /d /r %a in (failed) do #if exist %a\nul #for %b in (%a\*) do #move %b %destination%\%~nxb
or, translated into a bat file and spiced it up a bit
pushd %sourceroot%
for /d /r %%a in (failed) do (
if exist %%a\nul (
for %%b in (%%a\*) do (
move %%b %destination%\%%~nxb
)
)
)
popd
you'll have to figure out a way to rename the destination file to avoid name clashes.

Resources