windows batch: copy files in the loop - batch-file

I have a directory with .txt files. I need to loop over them and perform two tasks: pass the file into Oracle's stored proc and move it into archive directory. For some reason second task does not work for me. What am I missing?
REM -----------------------------------------
REM first step changes file extension to .632
REM -----------------------------------------
for /f %%I in ('dir /b \\db01\load\*.txt') do (sqlplus.exe usr/pwd#DB #\\db01\sql\load.sql %%I)
for /f %%I in ('dir /b \\db01\load\*.632') do (move \\file01\archive)

Here's a couple of untested examples:
#Echo Off
PushD "\\db01\load" 2>Nul || Exit /B
For %%A In (*.txt *.632) Do (
If /I "%%~xA"==".txt" sqlplus usr/pwd#DB #"..\sql\load.sql" "%%A"
If /I "%%~xA"==".632" If Exist "..\..\file01\archive\" Move /Y "%%A" "..\..\file01\archive" >Nul
)
PopD
 
#Echo Off
PushD "\\db01\load" 2>Nul || Exit /B
For %%A In (*.txt) Do sqlplus usr/pwd#DB #"..\sql\load.sql" "%%A"
If Exist "*.632" Move /Y "*.632" "..\..\file01\archive" >Nul
PopD
Additionally, depending upon your sqlplus command requirements, you may wish to look at the Start command usage information, start /?

Related

Batch script to delete all the subfolders inside specific folder in all remote servers and output as a text file

Here I am trying to execute a batch script which deletes subfolders under folder "updates" in all remote machines. List of servers are passed as input
(serverlist.txt)
echo off
for /f %%l in (C:\deleteauto\delrem\serverlist.txt) do
if exist C:\updates goto sub
if not exist C:\updates goto nofile
:sub
del /f /q "C:\updates\*.*"
for /d %%d in ("C:\updates\*.*") do rmdir /s /q "%%d"
echo folder is deleted in %%l >>c:\finaloutput.txt
:nofile
echo No folders in %%l >>c:\final output.txt
Can someone please help in rectifying the errors. Script executed but outputs nothing.
Try this code:
#echo off
for /f "tokens=*" %%l in (C:\deleteauto\delrem\serverlist.txt) do (
if exist "\\%%l\C$\updates" (
pushd "\\%%l\C$\updates"
del /f /q "*."
for /d %%d in ("*.") do rmdir /s /q "%%d"
echo Folder is deleted on server: %%l>>finaloutput.txt
popd
) else (
echo Folder does not exist on server: %%l>>finaloutput.txt
)
)
Here's an example of how I may tackle the task:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "SvrLst=C:\deleteauto\delrem\serverlist.txt"
If Not Exist "%SvrLst%" GoTo :EOF
(For /F UseBackQ^ Delims^=^ EOL^= %%G In ("%SvrLst%"
) Do PushD "%%~G\C$\updates" 2>NUL && (
RD /S /Q . 2>NUL
Echo Instruction to empty directory applied on %%~G & PopD
) || Echo Directory path not found on %%~G) 1>"C:\finaloutput.txt"
You will note that I have not stated that the directory was emptied. Just because an instruction was applied, does not mean that it was successful at doing so. Unless you check that the \C$\updates directory is completely empty afterwards, you should not imply that it is.
Errors were rectified by #Fire Fox , Thank you! Modified slightly & it worked as expected.
Code:
#echo off
for /f "tokens=*" %%l in (C:\deleteauto\delrem\serverlist.txt) do (
if exist "\\%%l\C$\updates" (
pushd "\\%%l\C$\updates"
del /f /q "\\%%l\C$\updates\*.*"
for /d %%d in ("\\%%l\C$\updates\*.*") do rmdir /s /q "%%d"
echo Folder is deleted on server: %%l>>C:\finaloutput.txt
popd
) else (
echo Folder does not exist on server: %%l>>C:\finaloutput.txt
)
)

Batch deleting every file except partial files

I have a batch file, that constantly checks to see if there are any files in a directory:
#echo off
cls
mode 15,5
cd C:\Users\Toni\Downloads\
goto mark
:mark
set var=2
dir /b /a "Downloads\*" | >nul findstr "^" && (goto exin) || (goto mark1)
goto mark
:mark1
cls
#ping -n 10 localhost> nul
goto mark
:exin
start /B C:\Users\Toni\Downloads\Test\download.bat
exit
if ther are any files in this folder, it moves them.
#echo off
cls
cd C:\Users\Toni\Downloads\Downloads
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.rar C:\Users\Toni\Downloads\Archive
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.zip C:\Users\Toni\Downloads\Archive
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.exe C:\Users\Toni\Downloads\Setups_usw
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.msi C:\Users\Toni\Downloads\Setups_usw
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.mp3 E:\-_MUSIC_-\Musik
xcopy /Y C:\Users\Toni\Downloads\Downloads\*.wav E:\-_MUSIC_-\Musik
xcopy /S /E /Y /EXCLUDE:C:\Users\Toni\Downloads\Test\excludedfileslist.txt C:\Users\Toni\Downloads\Downloads\*.* C:\Users\Toni\Downloads\Sonstiges
goto err
:err
if errorlevel 1 ( dir /arashd >> "C:\Users\Toni\Downloads\Test\somefile.txt" 2>&1 ) else ( del /[!*.part] * )
goto end
:end
start /B C:\Users\Toni\Downloads\Test\run.cmd
exit
However, I do not want to move files that are in the process of downloading (ie. I don't want to move partial files with a .part extension).
I tried using an argument to the del command like so:
del /[!*.part] *
but it doesn't seem to work.
How can I avoid moving partial files with the .part extension?
I would probably look at the file extension (using "substitution of FOR variables").
SET "TARGET_DIR=C:\Users\Toni\Downloads\Downloads"
FOR /F "delims=" %%f IN ('dir /b "%TARGET_DIR%"') DO (
REM Ensure it doesn't have '.part' as an extension.
IF NOT "%%~xf"==".part" (
REM Ensure there's not a corresponding ".part" file.
IF NOT EXIST "%TARGET_DIR%\%%~f.part" (
DEL "%TARGET_DIR%\%%~f"
)
)
)
This will delete any file in TARGET_DIR that doesn't have ".part" as a filename extension or have a corresponding ".part" file. (In my experience downloaders that do the ".part" thing also reserve the name of the "finished" file as well, which you'd probably not want to delete.)
Another possible solution (shorter than #mojo's one):
#echo off
cd /d C:\Users\Toni\Downloads\Downloads
attrib +h *.part
for /f "delims=" %%A IN ('dir /b /A:-H') do del %%A
attrib -h *.part
This, will hide all .part files, delete all other files and remove again the hidden attribute.

Batch Script Delete Folders & Files (Except One) From Remote PCs

We have multiple workstations that we need to do this on, and would like to batch script it (PowerShell is not an option for this particular task).
On each PC, we need to kill a specific process ("univmgr.exe"), then delete all subfolders and files from the following parent directory: C:\DRS\TEMP, except one subfolder named "DGNUser10" (as well as excluding everything inside the DGNUser10 subfolder).
I'm able to get my test script to work when I run it locally on a single test machine:
#echo off
taskkill /f /im univmgr.exe /t
pushd "C:\DRS\TEMP" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"=="DGNUser10" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
But when I try to target a text file list of computers (list.txt), something is horribly wrong with my syntax, but I haven't yet been able to figure out what it is or how to fix it... Here's the current script I've been tweaking and testing:
:Start
cls
#echo off
for /f "tokens=*" %%A in (list.txt) do (
taskkill /f /im univmgr.exe /t
for /D %%D in ("C:\DRS\TEMP") do (
if /I not "%%~nxD"=="DGNUser10" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
)
Goto End
:End
Thanks to Squashman's gentle and spot-on leading, I was able to figure out what I needed to modify in my code in order to get the script working!
Here's the updated script:
:Start
cls
#echo off
for /f "tokens=*" %%A in (list.txt) do (
taskkill /s \\%%A /f /im univmgr.exe /t
pushd "\\%%A\c$\DRS\TEMP" || exit /B 1
for /D %%D in ("*") do (
if /I not "%%~nxD"=="DGNUser10" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
)
popd
)
Goto End
:End

Batch script - Quick recursive find of first folder starting from a root location

I want to make a script which finds as quickly as possible first folder named Target starting from root location D:\ and return its absolute path.
Folder structure of root location (D:\) can be like this:
-DontSearchHereFolder
-Folder1\Subfolder1\SSubfolder1\SSSubfolder1\
-Folder2\Subfolder2\SSubfolder2\TargetFolder
-DontSearchHereFolder2
-Folder3\Subfolder3\
Output of the script should be: D:\Folder2\Subfolder2\SSubfolder2\TargetFolder
For now I tried 2 methods but it's not quick enough:
(1)
set TG=\TargetFolder
set root=D:\
cd %root%
for /f "delims=" %%a in ('dir /b /s /a:d "%root%" ^|findstr /e /i "%TG%"') do set "folderpath=%%~a"
(2)
for /d /r "%root%" %%a in (*) do if /i "%%~nxa"=="%TG%" set "folderpath=%%a"
(1) is quicker than (2)
Question1: Is it possible to specify in command to search only for a maximum of 2 folders "down" from root (e.g. D:\Folder1\Subfolder1) ?
Question2: Is it possible to specify folders that should be automatically skipped (e.g. DontSearchHereFolder1&2)
This batch code is exactly for what you have asked for optimized for speed. It ignores the two specified directories on first level and it searches for the folders maximal two folder levels deep.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Root=D:"
set "TG=TargetFolder"
set "Ignore1=DontSearchHereFolder"
set "Ignore2=DontSearchHereFolder2"
for /D %%A in ("%Root%\*") do (
if "%%~nxA" == "%TG%" set "FolderPath=%%A" & goto Found
if not "%%~nxA" == "%Ignore1%" (
if not "%%~nxA" == "%Ignore2%" (
for /D %%B in ("%%A\*") do (
if "%%~nxB" == "%TG%" set "FolderPath=%%B" & goto Found
for /D %%C in ("%%B\*") do if "%%~nxC" == "%TG%" set "FolderPath=%%C" & goto Found
)
)
)
)
echo Could not find folder: "%TG%"
goto EndSearch
:Found
echo Found folder: "%FolderPath%"
:EndSearch
endlocal
The string comparisons are done case-sensitive for maximum speed.
No recursive subroutine calls are used as usually would be done for such tasks for maximum speed.
The comparisons for the directories to ignore in root folder are coded in batch script directly not using an array or a list of folder names for maximum speed.
Delayed expansion is not used for faster processing the command lines.
But much faster would be coding an executable in C/C++/C# for that task as processing the command lines of the batch file takes most likely the most time on searching for the folder.
Note: Command FOR ignores folders with hidden attribute set.
Well, I use for such tasks shareware tool Total Commander which supports searching only in selected folders for a specific folder not more than X levels deep extremely fast.
This should take into account all the limits indicated in the question, but unless a lot of folders are found inside the indicated exclusions, I don't think this should be faster, just give it a try
#echo off
setlocal enableextensions disabledelayedexpansion
set "source=d:\"
set "target=TargetFolder"
set "maxLevels=2"
set excludeFolders= "DontSearchHereFolder" "DontSearchHereFolder2"
for %%s in ("%source%") do for /f "tokens=*" %%f in ('
robocopy "%%~fs." "%%~fs." /l /nfl /njh /njs /nc /ns /s
/xd %excludeFolders% /lev:%maxLevels%
^| findstr /e /i /l /c:"\\%target%\\"
^| cmd /v /q /c"set /p .= &&(echo(!.!)"
') do echo "%%~f"
I think this is the fastest possible way to do this:
#echo off
setlocal EnableDelayedExpansion
if "%1" neq "" goto %1
set "root=D:\"
set "TG=TargetFolder"
set "exclude=/DontSearchHereFolder1/DontSearchHereFolder2/"
"%~F0" Input | "%~F0" Output > result.txt
set /P "folderpath=" < result.txt
del result.txt
echo First folder: %folderpath%
goto :EOF
:Input
cd "%root%"
for /D %%a in (*) do if "!exclude:/%%a/=!" equ "%exclude%" (
cd "%%a"
dir /B /S /A:D "%TG%" 2>NUL
cd ..
)
exit /B
:Output
set /P "folder="
echo "%folder%"
set "i=0"
for /F "tokens=2" %%a in ('tasklist /FI "IMAGENAME eq cmd.exe" /FO TABLE /NH') do (
set /A i+=1
if !i! equ 2 taskkill /PID %%a /F
)
exit /B
The folders to exclude are given in a slash-separated list; if this list is longer, the process run faster because more folders are skipped. The target folder is search in each one of the non-excluded folders via a dir /B /S /AD "%TG%" command, that is faster than any combination of other commands. The process ends as soon as the first folder name is received in the rigt side of the pipe; the remaining processing at left side of the pipe is cancelled via a taskkill command.

Excluding a folder in a recursive copy in Batch

Basically what's going on is that we are migrating about 50 desktops from XP to 7. I cannot install any extra programs to complete this task. What I am doing is writing a script that copies the Desktop, Favourites, and My Documents, along with a few specific file types from the originating machine to a shared drive for the user. Which later will be able to have all files moved to the new machine they are getting. I'm trying to recursively search through Windows and get all .pst files and other files you will see in the script, and back them up to a folder on the share (but not in a directory structure, I just want all the files in a single directory no matter where they originated from) with the exception of My Documents. Anything they have put in My Documents should be excluded in the search. Anyway, this is what I started with:
#echo off
cls
set USRDIR=
set SHARE=
set /P USRDIR=Enter Local User Directory:
set /p SHARE=Enter Shared Drive Name:
set UPATH="c:\Documents and Settings\%USRDIR%"
set SPATH="g:\!MIGRATION"
set ESRI="%UPATH%\Application Data\ESRI"
net use g: /delete
net use g: \\server\%SHARE%
md %SPATH% %SPATH%\GIS %SPATH%\Outlook %SPATH%\Desktop %SPATH%\Documents %SPATH%\Favorites
if exists %ESRI% md %SPATH%\ESRI
md %SPATH%\misc %SPATH%\misc\GISfiles %SPATH%\misc\XMLfiles %SPATH%\misc\CSVfiles
for /R %%x in (*.mxd) do copy "%%x" "%SPATH%\GIS\"
for /R %%x in (*.dbf) do copy "%%x" "%SPATH%\misc\GISfiles\"
for /R %%x in (*.xml) do copy "%%x" "%SPATH%\misc\XMLfiles\"
for /R %%x in (*.csv) do copy "%%x" "%SPATH%\misc\CSVfiles\"
for /R %%x in (*.pst) do copy "%%x" "%SPATH%\Outlook\"
if exist %ESRI% xcopy /y /d /s /i /z %ESRI% %SPATH%\ESRI && echo ESRI YES || ESRI NO
xcopy /y /d /s /i /z "%UPATH%\Desktop" "%SPATH%\Desktop" && echo DESK YES || DESK NO
xcopy /y /d /s /i /z "%UPATH%\My Documents" "%SPATH%\Documents" && echo DOCS YES || DOCS NO
xcopy /y /d /s /i /z "%UPATH%\Favorites" "%SPATH%\Favorites" && echo FAVS YES || FAVS NO
echo "Script Complete!"
pause
I then decided that I wanted to exclude My Documents just in case so I don't end up with a bunch of duplicates where anything they put in My Documents ends up getting copied twice. So I changed that recursive block to this:
for /R %%x in (*.mxd) do xcopy /y /d /z /exclude:"\My Documents\" "%%x" "%SPATH%\GIS\"
for /R %%x in (*.dbf) do xcopy /y /d /z /exclude:"\My Documents\" "%%x" "%SPATH%\misc\GISfiles\"
for /R %%x in (*.xml) do xcopy /y /d /z /exclude:"\My Documents\" "%%x" "%SPATH%\misc\XMLfiles\"
for /R %%x in (*.csv) do xcopy /y /d /z /exclude:"\My Documents\" "%%x" "%SPATH%\misc\CSVfiles\"
for /R %%x in (*.pst) do xcopy /y /d /z /exclude:"\My Documents\" "%%x" "%SPATH%\Outlook\"
Anyway, my question is this, is this the most efficient way of doing this? Is there a better way? I'm curious because I have no one here to bounce ideas or anything off of, I'm the sole on site support here. If someone sees a better way or thinks this is how they would do it, please let me know. There are a bunch more filetypes in there, but I removed most of them so the code sample wasn't so long, left enough to get the point across.
EDIT: Just to make it clear, I am not the IT Department for this organization. I'm a technical support liaison for the department to a separate IT division. Our actual IT department calls this a migration, but it's more or less a simple "lets in stall new machines without doing anything to prepare for it" sort of soup sandwich operation. I can't install, remove, or change the systems in any way, I can only backup the files.
Usually, the best option is reduce processing in batch files to the minimum, leaving as much as possible to commands. But if you have to iterate over the file system several times, it is better to do only one pass and process in batch.
Adapted from a more general batch. I have made changes to adjust to what you need, but somethings more specific (your ESRI folder) are not added. Adapt as needed.
#echo off
setlocal enableextensions enabledelayedexpansion
rem Ask for share name
set /P share=Enter Shared drive name:
if "%share%"=="" (
call :error "No share name provided"
goto endProcess
)
rem Configure target of copy
set target=g:
rem Connect to target
net use %target% /delete
net use %target% \\server\%share%
if not exist %target% (
call :error "No connection to server"
goto endProcess
)
rem Configure directory by extension
set extensions=.mxd .dbf .xml .csv .pst
set .mxd=GIS
set .dbf=misc\GISFiles
set .xml=misc\XMLFiles
set .csv=misc\CSVFiles
set .pst=Outlook
rem adjust target of copy to user name
set target=%target%\!MIGRATION\%username%
if not exist "%target%" (
mkdir "%target%"
)
rem Configure source of copy
set source=%userprofile%
if not exist "%source%" (
call :error "User profile directory not found"
goto endProcess
)
rem Resolve My Documents folder
call :getShellFolder Personal
set myDocPath=%shellFolder%
if not exist "%myDocPath%" (
call :error "My Documents directory not found"
goto endProcess
)
rem Ensure target directories exists
mkdir "%target%" > nul 2>nul
for %%e in ( %extensions% ) do mkdir "%target%\!%%e!" >nul 2>nul
rem We are going to filter file list using findstr. Generate temp file
rem with strings, just to ensure final command line is in limits
rem This will contain not desired folders/files or anything that will be
rem copied later
set filterFile="%temp%\filter.temp"
(
echo %myDocPath%
echo \Temporary Internet Files\
echo \Temp\
) > %filterFile%
rem Process user profile, excluding My Documents, IE Temp and not needed extensions
for /F "tokens=*" %%f in ('dir /s /b /a-d "%source%" ^| findstr /v /i /g:%filterFile% ^| findstr /i /e "%extensions%" ') do (
call :processFile "%%~xf" "%%f"
)
rem Now, process "especial" folders
mkdir "%target%\Documents"
xcopy /y /d /s /i /z "%myDocPath%" "%target%\Documents"
call :getShellFolder Desktop
if exist "%shellFolder%" (
mkdir "%target%\Desktop"
xcopy /y /d /s /i /z "%shellFolder%" "%target%\Desktop"
if errorlevel 1 (
call :error "Failed to copy desktop files"
)
)
call :getShellFolder Favorites
if exist "%shellFolder%" (
mkdir "%target%\Favorites"
xcopy /y /d /s /i /z "%shellFolder%" "%target%\Favorites"
if errorlevel 1 (
call :error "Failed to copy favorites"
)
)
rem Finish
goto :endProcess
rem ** subroutines *******************************************
:processFile
rem retrieve parameters
rem : %1 = file extension
rem : %2 = file
set ext=%~1
set file=%~2
rem manage .something files
if "%ext%"=="%file%" (
set file=%ext%
set ext=
)
rem manage no extension files
if "%ext%"=="" (
rem WILL NOT COPY
goto :EOF
)
rem determine target directory based on file extension
set extCmd=%%%ext%%%
for /F "tokens=*" %%d in ('echo %extCmd%^|find /v "%%" ' ) do set folder=%%d
if "%folder%"=="" (
rem file extension not in copy list
goto :EOF
)
copy /y /z "%file%" "%target%\%folder%" >nul 2>nul
if errorlevel 1 (
call :error "Failed to copy [%file%]"
) else (
echo %file%
)
goto :EOF
:getShellFolder
set _sf=%~1
set shellFolder=
if "%_sf%"=="" goto :EOF
for /F "tokens=2,*" %%# in ('reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "%_sf%" ^| find "%_sf%"') do (
set shellFolder=%%$
)
goto :EOF
:error
echo.
echo ERROR : %~1
echo.
goto :EOF
:endProcess
endlocal
exit /b
Try User State Migration Tool from Microsoft - I used it to move around 400 systems in less than 30 days. It takes a bit of setup for the script to run right, but it does a really really good job (and no program to install).
In default mode, it gets all PST files, Document, Desktop, Favorites, and a ton of other folders/registry settings. It also does this for all users on a computer (which can be limited by last login date or number of profiles) as long as the user running it is a local admin.
It may or may not work for what you need, but it's a good choice when designing a migration. It sounds like what you are trying to do can be done with USMT just by removing extra code in the ini files.
This checks and excludes any folder that ends with documents\ (or includes it, so subdirectories too) as IIRC the folder may be called \documents\ or \my documents\ and is case insensitive.
setlocal enabledelayedexpansion
for /R %%x in (*.mxd) do set "check=%%~dpx" & if /i "!check!"=="!check:documents\=!" copy "%%x" "%SPATH%\GIS\"
for /R %%x in (*.dbf) do set "check=%%~dpx" & if /i "!check!"=="!check:documents\=!" copy "%%x" "%SPATH%\misc\GISfiles\"
for /R %%x in (*.xml) do set "check=%%~dpx" & if /i "!check!"=="!check:documents\=!" copy "%%x" "%SPATH%\misc\XMLfiles\"
for /R %%x in (*.csv) do set "check=%%~dpx" & if /i "!check!"=="!check:documents\=!" copy "%%x" "%SPATH%\misc\CSVfiles\"
for /R %%x in (*.pst) do set "check=%%~dpx" & if /i "!check!"=="!check:documents\=!" copy "%%x" "%SPATH%\Outlook\"
endlocal

Resources