I inherited a set of batch files.
Bat1 called bat2 which called bat3.
Bat3 created an xml, which bat2 used to create an html and bat1 used that to create a pdf.
Finally bat1 copied the pdf to an output directory.
I've recently joined the three batch files into one and everything works exactly the same up to the final copy command, which fails stating the pdf cannot be found.
#echo off
pushd %~dp0
set sourceFile=%1
set xslt=%2
set outputFile=%3
for %%i in (%sourceFile%) do (
set documentName=%%~ni
)
::BATCH FILE 2 CALLED
::BATCH FILE 3 CALLED
echo Processing source file compose
java -cp lib\saxon9.jar; net.sf.saxon.Transform -s:%sourceFile% -xsl:conversion\compose.xsl -o:compose.xml
echo Processing source file catalog
java -cp lib\saxon9.jar; -s:compose.xml -xsl:conversion\catalog.xsl -o:catalog.xml
::END OF BATCH FILE 3
echo Processing source file to HTML
java -cp lib\saxon9.jar; net.sf.saxon.Transform -s:catalog.xml -xsl:conversion\html5.xsl -o:index.html
echo Bundling publication
mkdir %documentName%
xcopy /y "conversion\webapp\*" %documentName%\ /o /x /e /h /k
move index.html %documentName%\
copy source graphics into web application img res dir
for %%f in ("*.jpg" "*.png" "*.gif" "*.svg" "*.psd" "*.ai" "*.pdf") do copy "%%f" %documentName%\asset\img\
::END OF BATCH FILE 2
echo Running AHF
AHFCmd -extlevel 4 -d %documentName%\index.html -o %documentName%.pdf -f HTML -x 4 -i tool\AHF\AHFSettings(x64).xml -stdout
::EVERYTHING WORKS FINE TO HERE; %documentName%.pdf is created just as it was previously.
echo Moving %documentName%.pdf
copy %documentName%.pdf %outputFile% ::Error - The system cannot find the file specified.
popd
The line copy %documentName%.pdf %outputFile% hasn't changed. I have tried using CALL in front of the AHFCmd and JAVA commands but that makes no difference. I have tried dir /b /a-d just before the copy command and it lists the file I want to move in the current directory. What am I doing wrong?
Related
I'm new to this cmd/FTP command. I would like to create a new folder at my local directory using today's date and connect to FTP to download the specific file to the newly created folder. If I manually type in command one by one at cmd, it has no issue. But when I use a batch file to run, my command stopped at FTP.
setlocal enableextensions
set name=%date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4"_"job%
mkdir C:\%name%
cd C:\%name%
ftp
open 192.168.31.93
*user*
*password*
binary
cd *directory*
mget -i *.*
I did try to separate my command to two batches;
1. folder creation
2. FTP download but the file downloaded didn't go into the folder I created. the downloaded file went to C:\Document & Settings.
main batch file
#echo off
call rename.bat
ftp -i -s:ftp.txt
rename.bat
setlocal enableextensions
set name=%date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%"_job"
mkdir c:\%name%
cd c:\%name%
ftp.txt
open 192.168.31.93
*user*
*password*
binary
cd *directory*
mget *.*
close
Another method I try is using '!' when in FTP environment, then create a folder then exit back to FTP environment. This method again doesn't work with the batch file. Please help
It seems that with command extensions enabled, the working directory set by a child batch file is lost, then the batch file exits.
I'm not sure how to solve it, but you actually do not need the rename.bat file to be a separate file. This "main batch file" should work:
#echo off
setlocal enableextensions
set name=%date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%"_job"
mkdir c:\%name%
cd /d c:\%name%
ftp -i "-s:%~dp0\ftp.txt"
Also note the /d added to cd. Without that your batch will not work when started from another drive. You also have to use %~dp0 to refer to the batch file folder for the ftp.txt. As at the time ftp is called, you have changed to the target directory.
You possibly do not even need the command extensions to be enabled. So simply removing the setlocal enableextensions might solve the problem too. Though you still need the %~dp0 and /d.
I've decided to post this, although similar to the answer given, there are a couple of differences.
It creates the text file, then deletes it, (this keeps everything more portable).
I have corrected your directory name, (because of a typo).
#Echo Off
Set "Name=%DATE%"
Set "Name=%Name:~-10,2%-%Name:~-7,2%-%Name:~-4%_job"
MD "C:\%Name%" 2>Nul
CD /D "C:\%Name%" || Exit /B
( Echo open 192.168.31.93
Echo *user*
Echo *password*
Echo binary
Echo cd *directory*
Echo mget *.*
Echo close
)>"ftp.txt"
FTP -i -s:ftp.txt
Del "ftp.txt" 2>Nul
Exit /B
Below is a directory structure where I have to compress all *.txt files in the app* subdirectories into a RAR archive with current date in name with deletion of archived files and folders.
I am totally new on working on command line and writing batch scripts and know only some basics.
Are there any suggestions on how to solve this task using Rar or WinRAR?
E:
Data
Log
makeRar.bat
app1
1.txt
2.txt
3.txt
.
.
.
n.txt
app2
1.txt
2.txt
3.txt
.
.
.
n.txt
app3
1.txt
2.txt
3.txt
.
.
.
n.txt
.
.
.
appn
1.txt
2.txt
3.txt
.
.
.
n.txt
----------- After execution of makeRar.bat file -------------
E:
Data
Log
makeRar.bat
app1
4/1/2016_log.rar
app2
4/1/2016_log.rar
app3
4/1/2016_log.rar
I have an answer for this problem. But this solution is using a static path, and not a dynamic path. So when this batch file is executed, it produces the output exactly as wanted, but only for a specific app folder according to code below.
set loc="C:\Program Files\WinRAR"
cd /D %loc%
rar.exe a -r -agYYYY-MM-DD -df -ep %source%\app1\log_.rar %source%\app1\*.txt
source must be defined with path of source directory.
EDIT:
I found a better solution for this task for your directory structure by iterating two FOR loops where first is for getting current and subdirectories and second for getting files from subdirectories.
set "source=C:\Program Files\WinRAR"
for /R /D %%s in (.\*) do (
echo %%s
for %%F in (%%s\*.txt*) do (
"%source%\rar.exe" a -r -agYYYY-MM-DD -df -ep %%s\log_.rar %%F
)
)
pause
Based on your given information this should work. If RAR.exe is not in a folder in your PATH variable you will need to add that path to the PATH variable or provide the full path to the executable in the batch file.
#echo off
:: Get Date
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
SET "YYYY=%dt:~0,4%"
SET "MM=%dt:~4,2%"
SET "DD=%dt:~6,2%"
FOR /D %%G IN (app*) DO (
PUSHD "%%~G"
rar a %DD%%MM%%YYYY%_log.rar *.txt
del *.txt
POPD
)
There is the text file Rar.txt in program files folder of WinRAR which is the manual for console version Rar.exe. By viewing this file and first select the command to use – here it is a for add files to archive – and then reading from top to bottom about the switches and building the command line according to task requirements while reading makes it very easy to define the command line for compressing files into a RAR archive.
#echo off
for /D %%D in (app*) do (
echo Creating archive for %%D ...
"%ProgramFiles%\WinRAR\Rar.exe" a -agYYYY-MM-DD -cfg- -df -ep -idq -m5 -md4m -r- -s -y "%%D\log_.rar" "%%D\*.txt"
if errorlevel 1 pause
)
You can read about all the switches in text file Rar.txt.
Command PAUSE is only executed if an error occurred output by Rar.exe to console while all other messages are suppressed because of switch -idq.
The file name format for the RAR archives is log_YYYY-MM-DD.rar because this is much better than DD-MM-YYYY_log.rar once you have multiple such RAR archives in a directory because log_YYYY-MM-DD.rar displayed sorted alphabetically according to file name as by default on Windows results in getting the files also automatically sorted by date with oldest at top.
Rar deletes only the text files successfully added to the archive.
It is of course also possible to use WinRAR for compression:
#echo off
for /D %%D in (app*) do (
echo Creating archive for %%D ...
"%ProgramFiles%\WinRAR\WinRar.exe" a -agYYYY-MM-DD -cfg- -df -ep -ibck -m5 -md4m -r- -s -y "%%D\log_.rar" "%%D\*.txt"
)
WinRAR could create also ZIP archives instead of RAR archives which console version Rar does not support.
Rar switch -idq is replaced by WinRAR switch -ibck to run WinRAR minimized to system tray, i.e. in background. Error messages are displayed in a GUI window which is displayed automatically by WinRAR if an error occurs.
For help on WinRAR commands and switches which slightly differ from Rar switches click in WinRAR in menu Help on Help topics and click on tab Contents on item Command line mode and read the linked pages.
For understanding the used Windows commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
Look how easy it is to archive files using Rar or WinRAR. All really needed is a look into manual respectively help and little knowledge about standard commands of Windows listed on executing help in a command prompt window.
EDIT:
Both batch files above require that the batch file is in directory containing the subdirectories app* and this directory is the current directory. For executing this batch file for example as scheduled task with current directory being %SystemRoot%\System32 the batch code below would be better:
#echo off
for /D %%D in ("%~dp0app*) do (
echo Creating archive for %%~fD ...
"%ProgramFiles%\WinRAR\Rar.exe" a -agYYYY-MM-DD -cfg- -df -ep -idq -m5 -md4m -r- -s -y "%%~fD\log_.rar" "%%~fD\*.txt"
if errorlevel 1 pause
)
The command FOR searches for subdirectories app* now in directory of the batch file independent on what is the current directory. And passed to Rar is now name of archive file with full path and the file name pattern *.txt also with full path instead of using a path relative to current directory.
Well, the line if errorlevel 1 pause should be removed on using this batch file as scheduled task.
I am really new to batch file coding and need your help.
I've these directories:
c:\rar\temp1\xy.jpg
c:\rar\temp1\sd.jpg
c:\rar\temp1\dd.jpg
c:\rar\temp2\ss.jpg
c:\rar\temp2\aa.jpg
c:\rar\temp2\sd.jpg
c:\rar\temp3\pp.jpg
c:\rar\temp3\ll.jpg
c:\rar\temp3\kk.jpg
And I want to compress them to this
c:\rar\temp1\temp1.rar
c:\rar\temp2\temp2.rar
c:\rar\temp3\temp3.rar
How could this be done using WinRAR?
This can be done also with WinRAR without using a batch file, not exactly as requested, but similar to what is wanted.
Start WinRAR and navigate to folder c:\rar\.
Select the folders temp1, temp2 and temp3 and click on button Add in the toolbar.
As archive name specify now the folder for the RAR archives, for example c:\rar\.
Switch to tab Files and check there the option Put each file to separate archive.
Click on button OK.
WinRAR creates now three RAR archives with the file names temp1.rar, temp2.rar and temp3.rar in folder c:\rar\ with each archive containing the appropriate folder with all files and subfolders.
The list of files to add can be changed also on tab Files by entering for example *.txt in Files to exclude to ignore text files in the three folders on creating the archives.
And finally it makes sense to enter *.jpg on tab Files in edit field below Files to store without compression as JPEG files usually contain already compressed data and therefore WinRAR cannot really compress the data of the files further.
Here is also a batch file solution to move the files in all non-hidden subfolders of c:\rar\ and their subfolders into an archive file with name of the subfolder created in each subfolder as requested.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "RAREXE=Rar.exe"
if exist "%RAREXE%" goto CreateArchives
if exist "%ProgramFiles%\WinRAR\Rar.exe" set "RAREXE=%ProgramFiles%\WinRAR\Rar.exe" & goto CreateArchives
if exist "%ProgramFiles(x86)%\WinRAR\Rar.exe" set "RAREXE=%ProgramFiles(x86)%\WinRAR\Rar.exe" & goto CreateArchives
for /F "skip=2 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe query "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /v Path 2^>nul') do (
if /I "%%I" == "Path" if exist "%%~K\Rar.exe" for %%L in ("%%~K\Rar.exe") do set "RAREXE=%%~fL" & goto CreateArchives
)
for /F "skip=2 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe query "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /v Path 2^>nul') do (
if /I "%%I" == "Path" if exist "%%~K\Rar.exe" for %%L in ("%%~K\Rar.exe") do set "RAREXE=%%~fL" & goto CreateArchives
)
for /F "delims=" %%I in ('%SystemRoot%\System32\where.exe Rar.exe 2^>nul') do set "RAREXE=%%I" & goto CreateArchives
echo ERROR: Could not find Rar.exe!
echo/
echo Please define the variable RAREXE at top of the batch file
echo "%~f0"
echo with the full qualified file name of the executable Rar.exe.
echo/
pause
goto :EOF
:CreateArchives
set "Error="
for /D %%I in ("c:\rar\*") do (
echo Creating RAR archive for "%%I" ...
"%RAREXE%" m -# -cfg- -ep1 -idq -m3 -msgif;png;jpg;rar;zip -r -s- -tl -y -- "%%I\%%~nxI.rar" "%%I\"
if errorlevel 1 set "Error=1"
)
if defined Error echo/& pause
endlocal
The lines after set "RAREXE=Rar.exe" up to :CreateArchives can be omitted on definition of environment variable RAREXE with correct full qualified file name.
Please read the text file Rar.txt in the WinRAR program files folder for an explanation of RAR command m and the used switches. The question does not contain any information with which options the RAR archives should be created at all.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~f0 ... full name of batch file
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
reg /?
reg query /?
set /?
setlocal /?
where /?
See also single line with multiple commands using Windows batch file for an explanation of the operator &.
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on the three FOR command lines to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded reg or where command line with using a separate command process started in background.
This script can work as well:
#echo off
for %%a in ("C:\rar\temp1" "C:\rar\temp2" "C:\rar\temp3") do (
pushd "%%~a"
"C:\Program Files\WinRAR\rar.exe" a -r temp.rar *
popd
)
In Python v3.x:
Tested on Python v3.7
Tested on Windows 10 x64
import os
# NOTE: Script is disabled by default, uncomment final line to run for real.
base_dir = "E:\target_dir"
# base_dir = os.getcwd() # Uncomment this to run on the directory the script is in.
# Stage 1: Get list of directories to compress. Top level only.
sub_dirs_raw = [os.path.join(base_dir, o) for o in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, o))]
# Stage 2: Allow us exclude directories we do not want (can omit this entire section if we wish).
dirs = []
for d in sub_dirs_raw:
if "legacy" in d or "legacy_old" in d:
continue # Skip unwanted directories
print(d)
dirs.append(d)
# Stage 3: Compress directories into .rar files.
for d in dirs:
os.chdir(d) # Change to target directory.
# Also adds 3% recovery record using "-rr3" switch.
cmd = f"\"C:\Program Files\\WinRAR\\rar.exe\" a -rr3 -r {d}.rar *"
print(cmd)
# Script is disabled by default, uncomment this next line to execute the command.
# os.system(cmd)
Notes:
Script will do nothing but print commands, unless the final line os.system(cmd) is uncommented by removing the leading # .
Run the script, it will print out the DOS commands that it will execute. When you are happy with the results, uncomment final line to run it for real.
Example: if there was a directory containing three folders mydir1, mydir2, mydir3, it would create three .rar files: mydir1.rar, mydir2.rar, mydir3.rar.
This demo code will skip directories with "legacy" and "legacy_old" in the name. You can update to add your own directories to skip.
To execute the script, install Python 3.x, paste the lines above into script.py, then run the DOS command python script.py from any directory. Set the target directory using the second line. Alternatively, run the script using PyCharm.
This should work it also checks if the files were compressed alright.
You may need to change this part "cd Program Files\WinRAR" depending on where winrar is installed.
#echo Off
Cd\
cd Program Files\WinRAR
rar a -r c:\rar\temp1\temp1.rar c:\rar\temp1\*.jpg c:\rar\temp1\
if "%ERRORLEVEL%"=="0" ( Echo Files compressed
) Else Echo Failed
rar a -r c:\rar\temp2\temp2.rar c:\rar\temp2\*.jpg c:\rar\temp2\
if "%ERRORLEVEL%"=="0" ( Echo Files compressed
) Else Echo Failed
rar a -r c:\rar\temp3\temp3.rar c:\rar\temp3\*.jpg c:\rar\temp3\
if "%ERRORLEVEL%"=="0" ( Echo Files compressed
) Else Echo Failed
Pause
Below Script will compress each folder as a RAR file within the current directory with very useful info while compressing a large size of data.
#echo off
#for /D %%I in (".\*") do echo started at %date% %time% compressing... "%%I" && #"%ProgramFiles%\WinRAR\Rar.exe" a -cfg- -ep1 -inul -m5 -r -- "%%I.rar" "%%I\"
echo "Completed Successfully !!!"
pause
I have a parent folder with lots of folders (movies) underneath. Each folder has 1 file (the actual movie).
I would like some advice on a batch script that I can run to rename the folders to the file (movie) within excluding the extension (.avi)
e.g.
BEFORE
Parent (folder)
Folder 1
Movie 1.avi
Folder 2
Movie 2.avi
AFTER
Parent (folder)
Movie 1
Movie 1.avi
Movie 2
Movie 2.avi
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /ad "%sourcedir%\*" '
) DO (
FOR %%b IN ("%sourcedir%\%%a\*") DO IF /i "%%~na" NEQ "%%~nb" ECHO(REN "%sourcedir%\%%a" "%%~nb"
)
GOTO :EOF
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.
You would need to set your directory as sourcedir. I set my testing directory.
The following batch file does the job:
#echo off
if exist "%TEMP%\RenameFolders.bat" del "%TEMP%\RenameFolders.bat" >nul
cd /D "Complete\path\to\parent\folder"
for /R "Complete\path\to\parent\folder" %%I in (*.avi) do echo ren "%%~dpI" "%%~nI">>"%TEMP%\RenameFolders.bat"
if exist "%TEMP%\RenameFolders.bat" (
call "%TEMP%\RenameFolders.bat"
del "%TEMP%\RenameFolders.bat" >nul
)
"Complete\path\to\parent\folder" must be modified twice in the batch file by real parent folder path.
The main job is done by command FOR. Run in a command prompt window for /? to get information about option
/R ... recursive folder/file scan, and
%%~dpI ... drive and path of file, and
%%~nI ... name of file without path and file extension.
For each *.avi file the command echo is executed to create the rename command used later to rename the folder containing the *.avi file to the name of the *.avi file.
It is not possible to do the folder rename directly within the FOR loop as it is not possible to rename a folder while it is the current working directory for a running process. Each folder is the current working directory for the batch process while FOR is running.
The command CD in third line just makes sure that the working directory is set to parent folder of all the subfolders to rename to avoid that renaming a folder fails because the batch file is started from one of the subfolders.
The second line just makes sure there is no file RenameFolders.bat in the folder for termporary files for example when terminating this batch file once by click on button X while command FOR is currently running.
After command FOR processed recursively all *.avi files and a line with command ren was appended to file RenameFolders.bat for each file, this created batch file is called which renames now the folders.
Last the batch file temporarily created is deleted as not needed anymore.
I am trying to create a batch file that gets a zipped folder for that particular date (v_date) from the sftp site and then unzip them. The zip file contains five files that are text documents. I have written batch scripts that successfully get the zip file from the remote site and save a copy of it on the local drive. I need to incorporate the unzip part in to my script.
SET v_date=%1
if [%v_date%] == [] SET v_date=%date:~10,4%%date:~4,2%%date:~7,2%
echo option batch continue>FTP_File_Get.txt
echo option confirm off>>FTP_File_Get.txt
echo open Target>>FTP_File_Get.txt
echo lcd "M:\Development\Data History\File" >> FTP_File_Get.txt
echo cd /Export/File >> FTP_File_Get.txt
echo get /Export/File/Filename_%v_date%.zip "M:\Development\DataHistory\Filename_%v_date%.zip">>FTP_File_Get.txt
echo exit>>FTP_File_Get.txt
M:\temp\apps\WinSCP\winscp.com/script="M:\Development\SFTPBatchFiles\FTP_File_Get.txt"
del FTP_File_Get.txt
This is my code to UNZIP:
SET v_date=%1
if [%v_date%] == [] SET v_date=%date:~10,4%%date:~4,2%%date:~7,2%
cd "M:\Development\Data History\"
::SET v_file="M:\Development\Data History\Filename_%v_date%.zip"
::unzip -o %v_file%
"C:\Program Files\7-Zip\7z.exe" e "Filename_%v_date%.zip"
I need to move the extracted files (6 Files) into their respective folders, Any help is greatly appreciated
To unzip the files you can use this command line:
"C:\Program Files\7-Zip\7z.exe" e "filename.zip"
#echo off
set "source=%userprofile%\Desktop\basanta\Automation\a"
set "target=%userprofile%\Desktop\basanta\Automation\b"
FOR %%A IN ("%source%\*.gz") DO (
"%programfiles%\7-zip\7z.exe" x "%%~A" -o"%target%\%%~pA"
del "%%~A" /Y
)
Use the above code by saving it to .bat file extension
Remember %userprofile% is for the directory, %programfiles% for the program files set as a variable in windows
hope that helps