Am trying to extract a RAR file to a directory (C:\autoexe\source). Here the "autoexe" folder name changes everyday. The fullname does not change, the constant thing is "auto" in the string "autoexe", the exe part changes. I tried the below
for /f "delims=" %%a in ('dir /b "%cd%\samples\package.rar"') do start "" "%ProgramFiles%\WinRAR\WinRAR.exe" x -ibck "%cd%\samples\package.rar" *.* "%cd%\auto * \source"
This commented batch code with error handling should do the job:
#echo off
rem Get name of first non hidden subfolder starting with auto in current folder.
for /D %%I in (auto*) do set "FolderName=%%I" & goto CheckArchive
echo Error: There is no auto* folder in: "%CD%"
echo/
pause
goto :EOF
:CheckArchive
if exist "samples\package.rar" goto ExtractArchive
echo Error: There is no file "package.rar" in subfolder "samples" of
echo folder: "%CD%"
echo/
pause
goto :EOF
:ExtractArchive
"%ProgramFiles%\WinRAR\UnRAR.exe" x -c- -idq -y -- "samples\package.rar" "%FolderName%\"
if not errorlevel 1 goto :EOF
echo/
echo/
pause
Read text file Rar.txt in program files folder of WinRAR for details on the used switches on UnRAR command line or run UnRAR.exe from within a command prompt window without any option to get displayed a brief help on how to use this freeware console application.
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.
echo /?
for /?
goto /?
if /?
pause /?
set /?
Read answer on Single line with multiple commands using Windows batch file for an explanation of & operator. And read the Microsoft support article Testing for a Specific Error Level in Batch Files.
Related
I'm trying to write a batch file that returns the most recent file in a directory without using a for loop. I tried a lot but it's not working.
So is there a approach that we can get the most recent file without using for loop?
#echo off
cd D:\Applications
for /f "delims=" %%i in ('dir /b/a-d/od/t:c') do set RECENT="%%~nxi"
echo ..... starting jar........
start java -jar %RECENT%
echo ....jar started.....
exit 0
The execution gets stuck at start java and it does not go to next line or exit 0.
There can be used the following code using command FOR:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D "D:\Applications" 2>nul || (echo ERROR: Directory D:\Applications does not exist.& goto EndBatch)
for /F "eol=| delims=" %%i in ('dir /A-D /B /O-D /TC 2^>nul') do set "RECENT=%%i" & goto StartJava
echo WARNING: Could not find any file in directory: "%CD%"& goto EndBatch
:StartJava
if exist %SystemRoot%\System32\where.exe %SystemRoot%\System32\where.exe java.exe >nul 2>nul
if errorlevel 1 echo ERROR: Could not find java.exe. Check environment variable PATH.& goto EndBatch
echo ..... Starting jar .....
start "Running %RECENT%" java.exe -jar "%RECENT%"
if not errorlevel 1 echo ..... jar started .....
:EndBatch
if errorlevel 1 echo/& pause
endlocal
There is some error handling also added to the code.
Please note that the creation date is the date of a file on being created in the current directory. So if a file is copied from directory X to directory Y, its last modification date is not modified, but the file has a new creation date in directory Y which is newer than its last modification date.
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.
cd /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
set /?
setlocal /?
start /?
where /?
See also:
Single line with multiple commands using Windows batch file
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
I'm not sure why you don't want to use the most powerful command in cmd, but for the sake of answering your question:
dir /o-d /b "C:\my folder\*" >tmp
<tmp set /p "latest="
del tmp
echo the latest file is %latest%
:exe
dir /a plugins
cls
set /p load="Which file do you want to load?: "
if exist plugins\%load%.bat goto loadtrue
if not exist plugins\%load%.bat goto loadfail
:loadfail
cls
echo error, file does not exist or you typed the file name wrong, try again
pause
goto exe
:loadtrue
cls
start %load%.bat
pause
goto terminal
Here is a batch file with comments which are the lines starting with rem:
#echo off
:UserPrompt
cls
rem Output the names of all batch files in subdirectory plugins in directory
rem of this batch file without file extension and next an empty line.
for /F "eol=| delims=" %%I in ('dir "%~dp0plugins\*.bat" /A /B 2^>nul') do echo %%~nI
echo/
rem Make sure the environment variable Load is not defined by chance
rem for example by a previous execution of this batch file in same
rem Windows command prompt window.
set "Load="
rem Prompt the user for the batch file name to load respectively execute.
set /P "Load=Which file do you want to load? "
rem Has the user input anything at all?
if not defined Load goto UserPrompt
rem Remove all double quotes from input string.
set "Load=%Load:"=%"
rem Is there anything left after removing all double quotes?
if not defined Load goto UserPrompt
rem Is there a batch file with user input name in subdirectory plugins
rem in the directory containing this batch file?
if exist "%~dp0plugins\%Load%.bat" goto StartPlugin
echo/
echo Error: The file name was typed wrong.
echo Please try it again.
echo/
pause
goto UserPrompt
:StartPlugin
cls
rem Start a separate command process for execution of the user selected
rem batch file with window title of console window set to name of batch
rem file and current directory set to subdirectory plugins of the
rem directory containing this batch file.
start "%Load%" /D"%~dp0plugins" ".\%Load%.bat"
pause
goto Terminal
:Terminal
I recommend to read in addition to the comments:
What does %~dp0 mean, and how does it work?
What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
Please note that the directory path referenced with %~dp0 always ends with a backslash and therefore concatenation of this path with a directory or file name should be done without an additional backslash as shown in code above even if it makes the file/folder strings more difficult to read.
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.
cls /?
dir /?
echo /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
start /?
I want to automate compressing multiple files in a single directory, each with the same password, from the command line or with an app.
file1 -> file1(w/password).rar
file2 -> file2(w/password).rar
file3 -> file2(w/password).rar
The answer in Packing (WinRAR) with a password on a group of files is close to what I want, but way too complicated for my needs.
I know the reverse can be done easily from the command line.
Any thoughts? Thanks.
Here is a batch code for this simple task with an extra bonus:
The working directory can be passed to the batch file as first parameter.
The current directory is used if the batch file is started with no parameter.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "WorkingDirectory="
if "%~1" == "" goto ArchiveFiles
set "WorkingDirectory=%~1"
if "%WorkingDirectory:~-1%" == "\" (
if exist "%WorkingDirectory%*" pushd "%WorkingDirectory%" & goto ArchiveFiles
) else (
if exist "%WorkingDirectory%\*" pushd "%WorkingDirectory%" & goto ArchiveFiles
)
echo Directory "%WorkingDirectory%" does not exist.
endlocal
goto :EOF
:ArchiveFiles
for /F "delims=" %%I in ('dir /A-D /B * 2^>nul') do (
if /I not "%%~xI" == ".rar" (
"%ProgramFiles%\WinRAR\Rar.exe" a -# -cfg- -ep1 -idq -m5 -ma4 "-pPassword" -r- -s- -y -- "%%~nI.rar" "%%~fI"
)
)
if not "%WorkingDirectory%" == "" popd
endlocal
This batch file ignores *.rar files already existing in the directory.
Open in program files folder of WinRAR the text file Rar.txt for details on used command a and the used switches.
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 %~1
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
popd /?
pushd /?
set /?
setlocal /?
Read also the Microsoft article about Using Command Redirection Operators explaining 2>nul whereby in this code the redirection operator > must be escaped with caret character ^ to be first interpreted as literal character on parsing FOR command line and as redirection operator on execution of DIR by FOR.
And read also the answer on Single line with multiple commands using Windows batch file to understand the meaning of operator & as used here on two command lines.
I have the following MS Windows batch file code:
#echo off
cd\
dir/s *.docx *.xlsx *.ppt *.docx
SET /p input= %data% "
copy "%data%" C:\abc\
pause
This command shows all 4 types of extension list all over drives, but I want to take input from user and then copy to the desired location.
What am I missing?
Your main mistake is assigning the string entered by the user of the batch file to environment variable input but referencing on command copy the environment variable data which is not defined at all and therefore %data% is replaced twice before execution of the command line by nothing.
What about using this batch code?
#echo off
rem The next 2 commands are commented out as not needed for this task.
rem cd \
rem dir /s *.doc *.docx *.xlsx *.ppt
setlocal EnableExtensions EnableDelayedExpansion
:UserPrompt
echo/
echo Enter the file name with complete path or drag and drop
echo the file to copy from Windows Explorer over this window.
echo/
set "FileName=""
set /p "FileName=Enter file name: "
echo/
rem Remove all double quotes from entered string.
set "FileName=!FileName:"=!"
rem Has the user entered any file name at all?
if "!FileName!" == "" goto UserPrompt
rem Does the file really exist?
if exist "!FileName!" goto CopyFile
echo Error: The specified file does not exist.
echo/
goto UserPrompt
:CopyFile
copy "!FileName!" C:\abc\
echo/
endlocal
pause
Read the answer on Why is string comparison after prompting user for a string/option not working as expected? for an explanation on all the extra code used here.
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.
copy /?
echo /?
endlocal /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
I am trying to use WinRAR to compress all my different folders individually.
Example of folder content before
c:\projects\test
c:\projects\country
c:\projects\db
and after running the batch file
c:\backup\test.rar
c:\backup\country.rar
c:\backup\db.rar
I am trying the following command in a batch file. But it compresses all the folders in the projects folder being into the backup archive:
for /f "delims==" %%D in ('DIR C:\projects /A /B /S') do (
"C:\Program Files\WinRAR\WinRAR.EXE" m -r "c:\backup\projects.rar" "%%D"
)
c:\backup\projects.rar contains all the files which I want in separate archives.
How to modify the 3 lines in batch file to get the desired archives?
I think you need to change a couple things.
Change /A to /AD to get just the directories.
Remove the /S so you will only get the top-level directories in C:\Projects.
Inside your FOR loop, change the "c:\backup\projects.rar" to C:\Backup\%%D.rar"
WARNING: This code is untested.
FOR /F "DELIMS==" %%D in ('DIR C:\projects /AD /B') DO (
"C:\Program Files\WinRAR\WinRAR.EXE" m -r "C:\Backup\%%D.rar" "%%D"
)
Here is a batch file for more general usage of this common task because the folder with the subfolders to archive can be specified as parameter on running the batch file. There can be used also case-insensitive the option /N on running the batch file to suppress the execution of command PAUSE on an error occurred which could be useful on running the batch file from within a command prompt window or on calling it from another batch file.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "BackupFolder=C:\Backup"
set "FolderToArchive=C:\projects"
rem The first or the sescond argument can be optionally /N
rem to suppress the execution of command pause on an error.
set "PauseCmd=pause"
if /I "%~2" == "/N" set "PauseCmd="
if /I "%~1" == "/N" set "PauseCmd=" & shift /1
if exist "%ProgramFiles%\WinRAR\Rar.exe" goto CheckFolder
echo/
echo Error: RAR executable "%ProgramFiles%\WinRAR\Rar.exe" does not exist.
echo/
%PauseCmd%
exit /B 22
rem Folder to archive can be optionally specified as parameter.
:CheckFolder
if not "%~1" == "" set "FolderToArchive=%~1"
rem Check the existence of the folder to archive.
if exist "%FolderToArchive%\*" goto CheckDestination
echo/
echo Error: Folder "%FolderToArchive%" does not exist.
echo/
%PauseCmd%
exit /B 20
rem Check existence of backup folder and create this folder
rem if not already existing with verification on success.
:CheckDestination
if exist "%BackupFolder%\*" goto CreateArchives
md "%BackupFolder%"
if not errorlevel 1 goto CreateArchives
echo/
echo Error: Folder "%BackupFolder%" could not be created.
echo/
%PauseCmd%
exit /B 21
rem Archive each subfolder in specified or default folder to archive
rem as separate archive with name of folder as archive file name and
rem with current date and an automatically incremented number with at
rem least two digits appended to the archive file name to be able to
rem create multiple archives on different days and even on same day.
rem Parent directory path of each subfolder is removed from archive.
rem The name of the subfolder itself is added to each archive. This
rem can be changed by replacing "%%D" with "%%D\" or "%%D\*". Then
rem the files and subfolders of the compressed folder would be added
rem to archive without the name of the compressed folder.
rem Best compression is used on creating a solid archive with 4 MB
rem dictionary size. All messages are suppressed except error messages.
rem The last modification time of the created archive file is set to
rem date and time of newest file inside the archive.
:CreateArchives
set "RarError=0"
(for /D %%I in ("%FolderToArchive%\*") do (
echo Archiving %%I ...
"%ProgramFiles%\WinRAR\Rar.exe" a -ag_YYYY-MM-DD_NN -cfg- -ep1 -idq -m5 -md4m -r -s -tl -y "%BackupFolder%\%%~nI.rar" "%%I"
if errorlevel 1 call :GetRarError
)) & goto CheckRarError
:GetRarError
echo/
echo/
if %ERRORLEVEL% GTR %RarError% set "RarError=%ERRORLEVEL%"
goto :EOF
rem Wait for a key press if an error occurred on creating an archive
rem file and the option to suppress the pause on error is not used.
:CheckRarError
if not defined PauseCmd goto EndBatch
if not %RarError% == 0 %PauseCmd%
rem Exit with highest exit code of any RAR execution.
:EndBatch
exit /B %RarError%
For the details on the used switches on Rar command line open text file Rar.txt in program files folder of WinRAR which is the manual for the console version Rar.exe and read the explanations for those switches.
Note: Command a (add to archive) is used in batch code above instead of m (move to archive).
The manual for using WinRAR.exe from within a batch file can be found in help of WinRAR on tab Contents under list item Command line mode.
There are some differences on list of switches between console and GUI version of WinRAR. For example WinRAR.exe supports also creating ZIP archives which Rar.exe does not support. Therefore WinRAR.exe supports the switch -af<type> which console version does not. The switch -idq (quiet mode) of console version is switch -ibck (run in background) for GUI version.
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 /?
echo /?
exit /?
for /?
goto /?
if /?
md /?
pause /?
rem /?
set /?
setlocal /?
shift /?
Note: Such an archiving can be also done with WinRAR by selecting in WinRAR the folders to archive, clicking on Add icon in toolbar, inserting C:\Backup\ on Archive name and enabling option Put each file to separate archive on tab Files. The other options used in the batch file above defined via switches can be found on the tabs General, Backup and Time.