Directory Names in Batch - batch-file

How can I store a directory name in a variable inside batch file??

set dirname=c:/some/folder
echo %dirname%
REM retrieve the last letter of the folder
REM and save it in another variable
set lastLetter=%dirname:~-1%
echo %lastLetter%

To return the directory where the batch file is stored use
%~dp0
%0 is the full path of the batch file,
set src= %~dp0
echo %src%
I've used this one when I expect certain files relative to my batch file.

Without more precisions it's difficult to help you...
Maybe you want the current directory?
set name=%CD%
echo %name%

Use the set command.
Example:
rem Assign the folder "C:\Folder1\Folder2" to the variable "MySavedFolder"
set MySavedFolder=C:\Folder1\Folder2
rem Run the program "MyProgram.exe" that is located in Folder2
%MySavedFolder%\MyProgram.exe
rem Run the program "My Second Program.exe" that is located in Folder 2 (note spaces in filename)
"%MySavedFolder%\My Second Program.exe"
rem Quotes are required to stop the spaces from being command-line delimiters, but the command interpreter (cmd.exe) will still substitute the value of the variable.
To remove the variable, assign nothing to the name:
set MySavedFolder=
Since you are inside a batch file, I suggest surrounding your variable usage with setlocal and endlocal at the end of the file; this makes your environment variables local to the batch file and doesn't pollute the global environment namespace.

To allow a script to determine its parent folder directory name:
#echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:\= %
FOR %%a IN (%CDIR%) DO (
SET CNAME=%%a
)
echo %CDIR%
echo %CNAME%
pause
Or, better yet:
#echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:~1,-1%
SET CDIR=%CDIR:\=,%
SET CDIR=%CDIR: =_%
FOR %%a IN (%CDIR%) DO SET "CNAME=%%a"
echo %CDIR%
SET CNAME=%CNAME:_= %
echo %CNAME%
pause

Related

How can i call resgen in a bat file if the file is edited?

I need to create a resource file using resgen.exe only if the file is edited.
I've found a way to do it, and i need to loop through all the Language available.
This is my script.
#echo on
echo ------------------------------
echo -- Starting a run of resgen --
echo ------------------------------
Set resourcesPath=%~1Resources\
Set configuration=%~2
Set platform=%~3
set landingPath=%~1bin\%configuration%\Resources\
echo %landingPath%
IF exist %landingPath% ( echo %landingPath% exists ) ELSE ( mkdir %landingPath% && echo %landingPath% created)
set obj[0].Resource="%landingPath%Strings.en-GB.resources"
set obj[0].Text="%resourcesPath%Strings.en-GB.txt"
set obj[1].Resource="%landingPath%Strings.ru-RU.resources"
set obj[1].Text="%resourcesPath%Strings.ru-RU.txt"
set obj[2].Resource="%landingPath%Strings.es-ES.resources"
set obj[2].Text="%resourcesPath%Strings.es-ES.txt"
FOR /L %%i IN (0 1 2) DO (
for %%x in ("%%obj[%%i].Text%%") do set date_of_filenameTxt=%%~tx
for %%x in ("%%obj[%%i].Resource%%") do set date_of_filenameRes=%%~tx
ECHO %date_of_filenameTxt:~0, 16%
ECHO %date_of_filenameRes:~0, 16%
IF "%date_of_filenameTxt:~0, 16%" == "%date_of_filenameRes:~0, 16%" call :same
call :notsame
:same
(ECHO "No Copy for the :" %%obj[%%i].Text%% )
call :end
:notsame
"%resourcesPath%resgen.exe" %%obj[%%i].Text%% %%obj[%%i].Resource%%
:end
)
The problem is on getting the string from the obj[], how should be the sintax?
i've found if i do as below, it works.
call echo resource = %%obj[0].Resource%%
The task could be done much easier with the following code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
echo ------------------------------
echo -- Starting a run of resgen --
echo ------------------------------
set "resourcesPath=%~1Resources\"
set "configuration=%~2"
set "platform=%~3"
set "landingPath=%~1bin\%configuration%\Resources\"
if exist "%landingPath%" echo "%landingPath%" exists.& goto ProcessFiles
mkdir "%landingPath%"
if exist "%landingPath%" echo "%landingPath%" created.& goto ProcessFiles
echo ERROR: "%landingPath%" could not be created!& goto EndBatch
:ProcessFiles
for %%I in ("%resourcesPath%Strings.*-*.txt") do (
set "RunResgen=1"
for %%J in ("%landingPath%%%~nI.resources") do if "%%~tJ" == "%%~tI" set "RunResgen="
if defined RunResgen "%resourcesPath%resgen.exe" "%%I" "%landingPath%%%~nI.resources"
)
:EndBatch
endlocal
The outer FOR loop searches in the directory Resources for non-hidden files matching the wildcard pattern Strings.*-*.txt. There could be used also the wildcard pattern Strings.*.txt or the pattern Strings.??-??.txt.
For a found text file there is first defined the environment variable RunResgen with string value 1 whereby the value does not matter.
Next is executed one more FOR processing the resource file in landing Resources directory. If that file does not exist at all, %%~tJ expands to an empty string which means the IF condition compares "" with something like "10.11.2021 19:00" and so the condition is not true. If the appropriate .resources file exists, its last modification time is compared with the last modification time of the .txt file. If the two file time stamps are equal, the environment variable RunResgen is undefined for the next IF condition because of no need to run resgen.exe for this pair of text and resources files.
The second IF condition checks the existence of the environment variable RunResgen and if this variable still exists because of .resources file does not exist at all or has not the same last modification time as the .txt file, the executable resgen.exe is executed with the two file names.
Please note that the file date/time format depends on the country setting of the used account. On my Windows machine the date/time format is dd.MM.yyyy hh:mm and for that reason the simple string comparison works with these sixteen characters plus the two surrounding quotes taken also into account on comparing the two strings.
resgen.exe must create the .resources file with last modification date/time explicitly set to last modification date/time of the .txt file or this code does not work at all.
There is usually used on Windows the archive file attribute do determine if a source file was modified since last processing it. But I suppose this is not possible here as one .txt file could be used for multiple .resources files for multiple configurations and platforms (wherever the environment variable platform is used in real batch file).
Well, the main code could be even more optimized by using just following single line:
for %%I in ("%resourcesPath%Strings.*-*.txt") do for %%J in ("%landingPath%%%~nI.resources") do if not "%%~tJ" == "%%~tI" "%resourcesPath%resgen.exe" "%%I" "%landingPath%%%~nI.resources"
The executable resgen.exe is executed on .resources file not existing at all or its last modification date/time is different to the last modification date/time of the .txt file.
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 /?
endlocal /?
for /?
goto /?
if /?
mkdir /?
set /?
setlocal /?
See also single line with multiple commands using Windows batch file for an explanation of the operator & to execute always a GOTO after an ECHO.

Rename a file by replacing few characters using Batch script

I'm new to batch scripting and need help here.
My file name along with path is
C:\test\My_Test_File_20201006.txt
and I want to rename it as
C:\test\My_File_20201006.txt
using batch script only. I cannot use PowerShell here.
#echo off
set Pattern="Test_File"
set Replace="File"
Rem accepts the filename as cmd line argument
set filename=%1
Rem Update filename
set targetfile=%filename:Pattern=Replace%
Rem Rename the file
Ren %filename% %targetfile%
Exit
Using the above code, My file is renamed as "File". Tried % around the Pattern & replace variables, but no luck. Not sure where I'm going wrong. Tried all possible solutions from the StackOverflow and other tutorials, but none helped.
Edit:
After the proposed solution, getting a syntax error. The code is as below:
#echo off
set "filename=%~nx1"
echo %filename%
echo "%~dp1"
echo "%~dp1%filename:statement_=%"
ren "%~dp1%filename%" "%~dp1%filename:Test_=%"
I call my script from cmd line as:
D:/Test> C:/script/rename.bat C:\test\My_Test_File_20201006.txt
The echo statement correctly prints filename, directory & filename with the directory. Facing issues in rename statement.
Output:
My_Test_File_20201006.txt
"C:\test\"
"C:\test\My_Test_File_20201006.txt"
The syntax of the command is incorrect.
Three things wrong here.
You cannot add the quotes as part of the variable's value. It will actually use them as part of the variable. set variables to have double quotes including the variable name. For instance instead of set Pattern="Test_File" rather do set "Pattern=Test_File"
You never used the variables you've set Replace and Pattern
You either need to enabledelayedexpansion or use call to do the replacement because of the multple % required.
#echo off
set "Pattern=Test_File"
set "Replace=File"
Rem accepts the filename as cmd line argument
set "filename=%~nx1"
Rem Update filename
setlocal enabledelayedexpansion
ren "%~dp1%filename%" "!filename:%Pattern%=%Replace%!"
Another method, seeing as you only replace Test_ in your example:
#echo off
set "filename=%~nx1"
ren "%~dp1%filename%" "%filename:Test_=%"
EDIT
Fixing your example as per the edit.
#echo off
set "filename=%~nx1"
echo %filename%
echo "%~dp1"
echo "%~dp1%filename:statement_=%"
ren "%~dp1%filename%" "%filename:Test_=%"

Batch renaming last few characters of files

I'm trying to create a batch file that would rename a bunch of files in a folder. These files would have a naming of something like: blah(lol).txt. There will always be a four letters, followed by an open bracket, three letters, and finally a close bracket.
I want the batch file to remove the bracketed part of the name of the file, ie. rename the file without the bracketed part.
for %%i IN (*.txt) DO (set name=%%~ni
set name2=%name:~1,4%
ren %%i %name2%)
Why doesn't this work?
Magoo provided an explanation as to why your script failed, as well as a working script.
But in your case, there is no need for a script. A simple REN command is all that is needed:
ren "????(???).txt" "????.*"
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "tokens=1,2,3delims=()" %%a IN (
'dir /b /a-d "%sourcedir%\*(*).*" '
) DO ECHO REN "%sourcedir%\%%a(%%b)%%c" %%a%%b%%c
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.
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.
simple but works from the folder with the files to be renamed.
#echo off
title Rename Bat
echo This bat must be in the folder that
echo contains the files to be renamed.
:begin
echo Enter File Name
set /p old=
echo Enter New Name
set /p new=
ren "%old%" "%new%"
echo File Renamed
ping -n 3 127.0.0.1 >NUL
goto begin
a much simpler approach ... try a for loop that cycles through all files in your folder
I'm going to use lol as an example of three letter word inside brackets as stated in your question
#echo off
for %%a in (*) do (
rename "%%a" "%%a(lol).exe"
)
to use this batch file you have to place it in the folder containing the files you wanna rename

Batch Extract path and filename from a variable

How can I extract path and filename from a variable?
Setlocal EnableDelayedExpansion
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
I want to do that without using any function or any GOTO.
is it possible?
#ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO to SET to set the variables rather thon ECHOing them...
See for documentation for a full list.
ceztko's test case (for reference)
#ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
You can only extract path and filename from (1) a parameter of the BAT itself %1, or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a.
in HELP CALL or HELP FOR you may find more detailed information:
%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file
And then try the following:
Either pass the string to be parsed as a parameter to a CALL
call :setfile ..\Desktop\fs.cfg
echo %file% = %filepath% + %filename%
goto :eof
:setfile
set file=%~f1
set filepath=%~dp1
set filename=%~nx1
goto :eof
or the equivalent, pass the filename as a local FOR variable
for %%a in (..\Desktop\fs.cfg) do (
set file=%%~fa
set filepath=%%~dpa
set filename=%%~nxa
)
echo %file% = %filepath% + %filename%
All of this works for me:
#Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
if you want infos from the actual running batchfile,
try this :
#echo off
set myNameFull=%0
echo myNameFull %myNameFull%
set myNameShort=%~n0
echo myNameShort %myNameShort%
set myNameLong=%~nx0
echo myNameLong %myNameLong%
set myPath=%~dp0
echo myPath %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%
more samples?
C:> HELP CALL
%0 = parameter 0 = batchfile
%1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters
Late answer, I know, but for me the following script is quite useful - and it answers the question too, hitting two flys with one flag ;-)
The following script expands SendTo in the file explorer's context menu:
#echo off
cls
if "%~dp1"=="" goto Install
REM change drive, then cd to path given and run shell there
%~d1
cd "%~dp1"
cmd /k
goto End
:Install
rem No arguments: Copies itself into SendTo folder
copy "%0" "%appdata%\Microsoft\Windows\SendTo\A - Open in CMD shell.cmd"
:End
If you run this script without any parameters by double-clicking on it, it will copy itself to the SendTo folder and renaming it to "A - Open in CMD shell.cmd". Afterwards it is available in the "SentTo" context menu.
Then, right-click on any file or folder in Windows explorer and select "SendTo > A - Open in CMD shell.cmd"
The script will change drive and path to the path containing the file or folder you have selected and open a command shell with that path - useful for Visual Studio Code, because then you can just type "code ." to run it in the context of your project.
How does it work?
%0 - full path of the batch script
%~d1 - the drive contained in the first argument (e.g. "C:")
%~dp1 - the path contained in the first argument
cmd /k - opens a command shell which stays open
Not used here, but %~n1 is the file name of the first argument.
I hope this is helpful for someone.

How to return to the original directory after invoking change directory in DOS batch?

I want to create a batch file, batch.bat, that accepts 2 mandatory arguments:
%1 represents a path relative to the current directory.
%2 represents a filaname.
Assume the current directory is father\me\.
User can use this batch as follows:
batch child/grandchild log
batch ../brother log
The job description of batch.bat is as follows.
Moves to %1 directory,
Iterates all *.tex file in the %1 directory.
Save the result in the directory before moving.
The following is the incomplete code:
rem batch.bat takes 2 arguments.
cd %1
dir /b *.tex > <original directory>\%2.txt
How to return to the original directory after invoking change directory in DOS batch?
If you want to RETURN to original directory, do the first change with PUSHD and return with POPD. That is, moves to %1 directory must be achieved with
PUSHD %1
instead of CD %1, and the return is achieved with
POPD
instead of CD where?
If you want to ACCESS the original directory after changed it, store it in a variable this way:
SET ORIGINAL=%CD%
and use %ORIGINAL% later, for example:
dir /b *.tex > %original%\%2.txt
Definitely PUSHD / POPD is the preferred way to do this. But there is a (undocumented?) feature of SETLOCAL / ENDLOCAL that accomplishes the same thing (in addition to everything else SETLOCAL does).
If you change directory after a SETLOCAL, then you will return to the original directory upon ENDLOCAL.
cd OriginalLocation
setlocal
cd NewLocation
endlocal
rem we are back to OriginalLocation
One other thing with SETLOCAL that is documented - Any SETLOCAL within a called batch or :label routine will be terminated with an implicit ENDLOCAL upon exiting the batch or routine. The implicit ENDLOCAL will return to the original folder just as an explicit ENDLOCAL.
cd OriginalLocation
call :ChangeLocation
rem - We are back to OriginalLocation because :ChangeLocation did CD after a SETLOCAL
rem - and there is an implicit ENDLOCAL upon return
exit /b
:ChangeLocation
setlocal
cd NewLocation
exit /b
I wouldn't recommend using SETLOCAL/ENDLOCAL instead of PUSHD/POPD. But it is a behavior you should be aware of.
Response to johnny's comment
It can get confusing when PUSHD/POPD and SETLOCAL/ENDLOCAL are combined. The ENDLOCAL does not clear the PUSHD stack, as evidenced by the following:
setlocal
cd test
#cd
pushd new
#cd
endlocal
#cd
popd
#cd
--OUTPUT--
D:\test>setlocal
D:\test>cd test
D:\test\test
D:\test\test>pushd new
D:\test\test\new
D:\test\test\new>endlocal
D:\test
D:\test>popd
D:\test\test
set ORIGINAL_DIR=%CD%
REM #YOUR BATCH LOGIC HERE
chdir /d %ORIGINAL_DIR%
You can always set %cd% to a variable before changing directories:
set current="%cd%"
cd "C:\Some\Other\Folder"
cd "%current%"
In most cases, creating a variable with the directory is used in Batch Scripts. If the script is semi-lengthy, I will define my variables in the beginning of the script that includes important paths, files, subs, and/or long commands.
#ECHO OFF
REM Variables
::Programs
SET save_attachments=C:\Program Files\APED\Program\save_attachments.vbs
SET sendemail=C:\Program Files\APED\Program\sendkeys.vbs
SET tb=C:\Program Files\Mozilla Thunderbird\thunderbird.exe
SET fox=C:\Program Files\Foxit Software\Foxit Reader\Foxit Reader.exe
SET spool=C:\WINDOWS\system32\PRNJOBS.vbs
::Directories
SET new=C:\Program Files\APED\New
SET printing=C:\Program Files\APED\Printing
SET finish=C:\Program Files\APED\Finish
SET messages=C:\Program Files\APED\Script_Messages
SET nonpdf=C:\Program Files\APED\NonPDFfiles
SET errorfiles=C:\Program Files\APED\Error Files
::Important Files
SET printlog=C:\Program Files\APED\Script_Messages\PrintLOG.txt
SET printemail=C:\Program Files\APED\Script_Messages\EmailPrintLOG.txt
SET errorlog=C:\Program Files\APED\Script_Messages\ErrorLOG.txt
SET erroremail=C:\Program Files\APED\Script_Messages\EmailErrorLOG.txt
SET movefiles=C:\Program Files\APED\Script_Messages\MoveFiles.txt
However, PUSHD and POPD are great solutions if it is short and sweet imo.

Resources