"if not exist" command in batch file - batch-file

I need to write some code in a windows batch file.
The interested part of this script should create a folder if this folder doesn't exist yet, but, if this folder already exists, it should NOT overwrite the content.
I tried something like this:
if not exist %USERPROFILE%\.qgis-custom (
mkdir %USERPROFILE%\.qgis-custom
xcopy %OSGEO4W_ROOT%\qgisconfig %USERPROFILE%\.qgis-custom /s /v /e
)
But I'm not sure if I'm doing it right.
Thank you

if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer

Related

Batch script - check to see if file exists from previous iteration, if not process [duplicate]

I have to create a .BAT file that does this:
If C:\myprogram\sync\data.handler exists, exit;
If C:\myprogram\html\data.sql does not exist, exit;
In C:\myprogram\sync\ delete all files and folders except (test, test3 and test2)
Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
Call other batch file with option sync.bat myprogram.ini.
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You can use IF EXIST to check for a file:
IF EXIST "filename" (
REM Do one thing
) ELSE (
REM Do another thing
)
If you do not need an "else", you can do something like this:
set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=
Here's a working example of searching for a file or a folder:
REM setup
echo "some text" > filename
mkdir "foldername"
REM finds file
IF EXIST "filename" (
ECHO file filename exists
) ELSE (
ECHO file filename does not exist
)
REM does not find file
IF EXIST "filename2.txt" (
ECHO file filename2.txt exists
) ELSE (
ECHO file filename2.txt does not exist
)
REM folders must have a trailing backslash
REM finds folder
IF EXIST "foldername\" (
ECHO folder foldername exists
) ELSE (
ECHO folder foldername does not exist
)
REM does not find folder
IF EXIST "filename\" (
ECHO folder filename exists
) ELSE (
ECHO folder filename does not exist
)
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not
know how to test if a file or folder exists and if it is a file or
folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini

Batch deleting folders from file.txt

I have a temp folder where files get loaded into and then systematically purged out. Job to clear out files failed and now I have a number of directories/files that need to be manually deleted. I have deletedirs.txt that contains the names of all the folders I need deleted. I have generated the following to delete the files and folders however the path is not always the same:
FOR /F %%i IN (C:\dirlist.txt) DO echo y| del "C:\Temp Files\*" & rmdir /s /q "C:\Temp Files\" %%i
The issue is as the temp files get loaded in they form their own subfolder(s) so I have the following structure:
C:\Temp Files\101\folder1
C:\Temp Files\101\folder2
C:\Temp Files\103\folder4
C:\Temp Files\455\folder3
deletedirs.txt contains the folder names (folder1, folder2, etc.)
My script is failing because its searching for "C:\Temp Files\folder1"
How can I get the script to find 'folder1' and remove it regardless of subfolder number (101, 103, etc.)?
#ECHO OFF
SETLOCAL
FOR /d %%a IN ("c:\temp\*") DO (
FOR /f "delims=" %%s IN (q48890405.txt) DO (
IF EXIST "%%a\%%s\." ECHO RD /S /Q "%%a\%%s"
)
)
GOTO :EOF
You would need to change the directoryname to suit your circumstances.
I used a file named q48890405.txt containing some dummy data for my testing.
The required RD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO RD to RD to actually delete the directories.
This should assign the subdirectory names to %%a in turn, then for each subdirectory found, read the names from the file into %%s. Then see whether a directory named %%a\%%s exists, and delete it if it does exist.
Note that your del "C:\Temp Files\*" will simply delete all of the files in "C:\Temp Files" over and over again. It really only needs to be done once (if that's what you had intended to do).
Removing the directory disposes of all of the files it contained, provided none are protected in some way (read-only or by UAC).

Batch command to delete everything (sub folders and files) from a folder except one file

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")

how to copy files from one directory to other in batch command

I wish to copy a file with extension .dyn which is located in each subfolder of main folder(T15_finished). I wish to copy it into respective subfolder at other location(T15). I have created that location using xcopy command. Here, .dyn file is being copied successfully in respective subfolder in T15 folder(see below code). Now, I have a file which has extension as .dynain which is located in the same subfolder as .dyn. And .dynain file is also getting copied which i don't want.
Please see following code which i have created. Can anyone tell me whats wrong ?
#echo off
xcopy D:\Master\SPRINGBACK\CPW\T15_finished D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15 /t
xcopy /e D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15
pause
Short file names. If you do a dir /x in the folder containing the .dynain file, you will see the 8.3 filename generated for the file, and it will have .dyn extension.
If you know the extensions of the conflicting files, you can use robocopy with /xf switch to indicate the files (*.dynain) to exclude, or you can generate a exclude file to use with xcopy /exclude:file (see xcopy /? for a explanation)
Or, you can generate the list of files to exclude
(for /f "tokens=" %%a in (
'dir /s /b "D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn" ^| findstr /v /i /e /l ".dyn"'
) do #echo(%%~nxa)>excludedFiles.txt
xcopy /exclude:excludedFiles.txt /e D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15
Or (as posted by foxidrive), copy all and then delete the non needed files.
The short filename is being matched as well as the long filename. That is the reason.
A solution is to use another command to delete the files:
del /s "D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15\*.dynain"

Batch file to copy directories recursively

Is there a way to copy directories recursively inside a .bat file? Is an example of this available?
Look into xcopy, which will recursively copy files and subdirectories.
There are examples, 2/3 down the page. Of particular use is:
To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:
xcopy a: b: /s /e
After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):
robocopy source_dir dest_dir /s /e
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
#echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Windows Batch File Looping Through Directories to Process Files?
I wanted to replicate Unix/Linux's cp -r as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e Copies directories and subdirectories, including empty ones.
/k Copies attributes. Normal Xcopy will reset read-only attributes.
/h Copies hidden and system files also.
/i If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q Quiet. Do not display file names while copying.
/b Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o Copies directory and file ACLs. (requires UAC admin)

Resources