adding directory to path environment variable - windows

My requirement is to add one of the directory to path environment variable in windows at the time of installing my application and remove the same from path environment variable at the time of uninstallation using batch file.
In one of the stackoverflow answer related to this suggested the following to add a directory to path environment variable.
setx path C:\Program Files (x86)\MyApp\
It is adding to path variable but when I try to add one more, it overwrites the existing value which I have added. How to avoid this?
How to remove the directory path which I have added from path environment variable?

You should be able to use the existing value of it like this:
setx PATH %PATH%;C:\Program Files (x86)\MyApp\
To remove it you could probably do something like this:
setx PATH=%PATH:;C:\Program Files (x86)\MyApp\=%
Which would substitute the path it was given with nothing to delete it.

You need to check if user's part of path variable is empty, e.g. for adding a directory as follows:
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_apppath=C:\Program Files (x86)\MyApp\"
set "_keyBase=HKLM\SYSTEM\CurrentControlSet\Control\Session Manager" machine
set "_keyBase=HKCU" user
set "_dataTyp="
set "_dataOld="
for /F "tokens=2,*" %%G in ('
reg query "%_keyBase%\Environment" -V path ^| findstr /I "\<path\>"
') do (
set "_dataTyp=%%G"
set "_dataOld=%%H"
)
if defined _dataOld (
set "_dataNew=%_apppath%;%_dataOld%"
) else (
set "_dataNew=%_dataOld%"
set "_dataTyp=REG_SZ"
)
rem debugging output: show script variables
set _
if /I "%~1" EQU "write" (
reg add "%_keyBase%\Environment" -V path -T %_dataTyp% -d "%_dataNew%" -F
) else (
rem debugging output
ECHO reg add "%_keyBase%\Environment" -V path -T %_dataTyp% -d "%_dataNew%" -F
)
ENDLOCAL
goto :eof
Note that I use reg add instead of setx command. See also this Rojo's answer for exhaustive explanation.
Output.
d:\bat> D:\bat\SO\42140086.bat
_apppath=C:\Program Files (x86)\MyApp\
_dataNew=C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote
_dataOld=D:\bare!;D:\Remote
_dataTyp=REG_EXPAND_SZ
_keyBase=HKCU
reg add "HKCU\Environment" -V path -T REG_EXPAND_SZ -d "C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote" -F
d:\bat> D:\bat\SO\42140086.bat write
_apppath=C:\Program Files (x86)\MyApp\
_dataNew=C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote
_dataOld=D:\bare!;D:\Remote
_dataTyp=REG_EXPAND_SZ
_keyBase=HKCU
The operation completed successfully.
d:\bat> D:\bat\SO\42140086.bat
_apppath=C:\Program Files (x86)\MyApp\
_dataNew=C:\Program Files (x86)\MyApp\;C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote
_dataOld=C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote
_dataTyp=REG_EXPAND_SZ
_keyBase=HKCU
reg add "HKCU\Environment" -V path -T REG_EXPAND_SZ -d "C:\Program Files (x86)\MyApp\;C:\Program Files (x86)\MyApp\;D:\bare!;D:\Remote" -F
d:\bat>
Above output shows that the only check if a key is empty does not suffice as running it twice would add the same directory twice as well.
However, checking if a path key (user or machine-wide) contains a particular directory is not such simple task. For instance, some entries in path contain a trailing \ backslash while others don't. Moreover, some entries in a path registry value of REG_EXPAND_SZ could be tangled in other environment variables e.g. %ProgramFiles%\SomeApp instead of C:\Program Files\SomeApp etc.
The following complex script TestPath.bat could help to analyse Windows path environment variables (note that it could show incorrect values if a path contains an exclamation mark ! due to enabled delayed expansion):
#ECHO OFF
set "HkcuEnv=HKCU\Environment"
set "HklmEnv=HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
SETLOCAL enableextensions enabledelayedexpansion
echo --- %date% %time% %~nx0 %*
if /I "%~1" EQU "dir" (
set path
Call :printPath path "" dir %~2
echo/
echo tested using the following findstr regex:
echo "%pathext:;=$ %$"
ENDLOCAL
goto :eof
)
set pathext
Call :duplicity pathext
Call :printPath path ""
Call :duplicity path
set "HKCU_type="
set "HKCU_path="
for /F "tokens=2*" %%G in (
'reg query HKCU\Environment /v Path 2^>NUL ^|findstr /I "path"'
) do (
set "HKCU_type=%%G"
set "HKCU_path=%%H"
)
Call :printPath HKCU_path %HKCU_type%
if /I "%HKCU_type%"=="REG_EXPAND_SZ" Call :printPath HKCU_path %HKCU_type% Expanded
set "HKLM_type="
set "HKLM_path="
set "qqqq=HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
for /F "tokens=2*" %%G in ('reg query "%qqqq%" /v Path^|findstr /I "path"'
) do (
set "HKLM_type=%%G"
set "HKLM_path=%%H"
)
Call :printPath HKLM_path %HKLM_type%
if /I "%HKLM_type%"=="REG_EXPAND_SZ" Call :printPath HKLM_path %HKLM_type% Expanded
echo/
pause
REM echo/
REM set HK
echo/
echo/Usage: %~nx0
echo/ %~nx0 dir
echo/ %~nx0 dir all
ENDLOCAL
goto :eof
:printPath
echo/
echo %~0 %~1 %~2 %~3 %~4
if "!%~1!" NEQ "" (
set "ggg="!%~1:;=" "!""
rem set "ggg=!ggg:\"="!"
for %%G in (!ggg!) do (
if /I "%~3" NEQ "expanded" (
if /I "%~3" EQU "dir" (
set "_partpath=%%~G"
if not "%~4"=="" (
echo/
echo "%%~G"
if /I "!_partpath:%SystemRoot%=!" EQU "%%~G" (
dir /B /A:-D "%%~G" | findstr /I "%pathext:;=$ %$"
echo errorlevel !errorlevel!
if errorlevel 1 pause
rem timeout /T 3 /NOBREAK >NUL
) else (
>NUL (dir /B /A:-D "%%~G" | findstr /I "%pathext:;=$ %$")
echo errorlevel !errorlevel! system default
if errorlevel 1 pause
)
) else (
if NOT "%%~G"=="" (
for /F %%g in ('
2^>NUL dir /B /A:-D "%%~G" ^| findstr /I "%pathext:;=$ %$" ^| find "." /C
') do echo "%%~G" %%g file(s^)
) else (
echo "%%~G" ? file(s^)
)
)
) else (
echo "%%~G"
)
) else (
call echo "%%~G"
)
)
)
goto :eof
:duplicity
echo/
echo %~0 %~1 %~2
set /A "ii=0"
set "ggg="!%~1:;=" "!""
set "ggg=!ggg:\"="!"
for %%G in (!ggg!) do (
set /A "ii+=1"
set /A "jj=0"
for %%g in (!ggg!) do (
set /A "jj+=1"
if /I "%%~G"=="%%~g" if !ii! LSS !jj! echo !ii!, !jj!: %%~g
)
)
goto :eof
REM TODO: unfinished procedure / incorrect output
:deflatePath
echo/
echo %~0 %~1 %~2
set "ggg="!%~1:;=" "!""
rem set "ggg=!ggg:\"="!"
set "NewPath="
for %%G in (!ggg!) do (
set "item=%%~G"
set "meti="
call :deflateItem "ProgramFiles(x86)"
if defined meti (
rem echo # !item!
) else (
call :deflateItem "ProgramFiles"
if defined meti (
rem echo # !item!
) else (
call :deflateItem "SystemRoot"
if defined meti (
rem echo # !item!
) else (
rem echo = !item:%%=%%%%!
)
)
)
if defined NewPath (
set "NewPath=!NewPath!;!item!"
) else (
set "NewPath=!item!"
)
)
echo !NewPath!
rem reg delete HKCU\Environment /v NewPath /f
rem setx NewPath "!NewPath!"
rem WARNING: The data being saved is truncated to 1024 characters.
rem reg query HKCU\Environment /v NewPath|findstr /I "NewPath"
goto :eof
:deflateItem
set "meti=!%~1!"
if "!meti!"=="!item!" (
set "item=%%%~1%%"
) else (
set "meti=!item:%meti%\=!"
if "!meti!" == "!item!" (
set "meti="
) else (
set "item=%%%~1%%\!meti!"
)
)
goto :eof

Related

Looping through %1 as a directory in batch?

I've searched the web for answers but can't seem to find an answer. I want the user to provide a directory and to be able to loop through it. I'm able to loop through the current directory like so:
#Echo off
for /r %%f in (*.*) do (
echo %%f
)
But then when I try to do the same by looping through %1, I can't get the result I'm looking for. What am I doing wrong? Here's where I'm at in the batch file:
#Echo off
if exist %1 (
for /r %%f in (%1) do (
echo %%f
)
) else (
echo "That directory does not exist."
)
I've tried using /D but all that did was echo the directory I provided like this:
FileCount C:\Users\Me\Desktop
> C:\Users\Me\Desktop
Edit: My goal for this program is to eventually count the number of files within the given directory. I expect the directory to be provided as it's absolute path and I'll be executing this file through cmd. Here's an example of the input I'm expecting.
FileCount C:\Users\Me\Desktop
And the desired output would be something like:
> Hello world.txt
> Cat.png
> There are 2 files within this directory.
Side-note: I don't want to filter out the output of the dir command, I want to do this with a for loop.
Here's what you asked for, plus the optional recurs feature. Note that this will miss hidden files and directories.
#setlocal EnableExtensions
#prompt=$G
#set _Error_Success=0
#set _Error_PathNotFound=3
#if "%~1" equ "/?" goto :Usage
#if "%~1" equ "" goto :Usage
#if "%~1" equ "/r" (#set _recurs=/r & #set _root=%~2) else (#set _root=%~1)
#if not exist "%_root%" goto :Oops
#set count=0
#pushd "%_root%"
#for %_recurs% %%f in (*) do #call :Counter "%%f"
#popd
#echo There are %count% entries within this directory.
#exit /b %_Error_Success%
:Counter
#set /a count+=1
#echo %~1
#exit /b %_Error_Success%
:Oops
#echo "That directory does not exist."
#exit /b %_Error_PathNotFound%
:Usage
#echo Usage: FileCount [/r] path
And this uses the dir command, without resorting to invoking findstr:
#setlocal EnableExtensions
#prompt=$G
#set _Error_Success=0
#set _Error_PathNotFound=3
#set _Error_InvalidParameter=87
#set _attributes=
#set _recurs=
#set _count=0
#if "%~1" equ "/?" #goto :Usage & #exit
#if "%~1" equ "" goto :Usage
#set _root=%~1
#if not exist "%_root%" goto :Oops
#shift
#pushd "%_root%"
for /f %%G in ('dir /B /A-d %1 %2 %_root%') do #call :Counter "%%G"
#popd
#echo There are %_count% entries within this directory.
#exit /b %_Error_Success%
:Counter
#set /a _count+=1
#echo %~1
#exit /b %_Error_Success%
:HandleOptions
:Oops
#echo "That directory does not exist."
#exit /b %_Error_PathNotFound%
:Usage
#echo Usage: FileCount [/A<Attributes>] [/S] rootPath
#echo Where <Attributes> corresponds to 'dir /A' optiions (see 'help dir')
#echo and /S will cause recursion into subdirectories of rootPath.
This example, uses a for loop, and does not use the dir command, as per your inexplicable request, but it does use xcopy to list and count the files within it instead:
#For %%G In ("%~1") Do #If "%%~aG" Lss "d" (If "%%~aG" GEq "-" (
Echo Error: File argument given, expected a directory.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1) Else (
Echo Error: Invalid argument, directory path expected.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1)
) Else Echo File content of "%~1":& For /F Delims^= %%H In (
'%SystemRoot%\System32\xcopy.exe "%~1" : /HIL') Do #Echo %%~nxH
#%SystemRoot%\System32\timeout.exe /T -1 & Exit /B 0
If you want it to recurse the input directory, then I'd suggest this very small modification:
#For %%G In ("%~1") Do #If "%%~aG" Lss "d" (If "%%~aG" GEq "-" (
Echo Error: File argument given, expected a directory.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1) Else (
Echo Error: Invalid argument, directory path expected.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1)
) Else Echo File content of "%~1":& For /F Delims^= %%H In (
'%SystemRoot%\System32\xcopy.exe "%~1" : /HILS') Do #Echo %%H
#%SystemRoot%\System32\timeout.exe /T -1 & Exit /B 0
Or with a little more work, outputting relative paths instead:
#For %%G In ("%~1") Do #If "%%~aG" Lss "d" (If "%%~aG" GEq "-" (
Echo Error: File argument given, expected a directory.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1) Else (
Echo Error: Invalid argument, directory path expected.
%SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1> NUL
Exit /B 1)
) Else Echo File content of "%~1":& For /F Delims^= %%H In (
'%SystemRoot%\System32\xcopy.exe "%~1" : /HILS') Do #(
Set "}=%%H" & SetLocal EnableDelayedExpansion
For %%I In ("!}:*%~1=.!") Do #EndLocal & Echo %%~I)
#%SystemRoot%\System32\timeout.exe /T -1 & Exit /B 0
setlocal enabledelayedexpansion
rem Put it into a folder that is in ENV PATH variable.
rem So, you can call it from wherever you want.
if not "%~1"=="" (
if exist "%~dpn1" (
set /a "filecount=0"
for /f "tokens=* delims=" %%f in ('dir /b "%~dpn1"') do (
echo %%f
set /a "filecount+=1"
)
echo:
echo In "%~dpn1" found !filecount! file^(s^).
) else (
echo:
echo [ERROR] Invalid input. Please specify:
echo 1. A full path.
echo 2. A folder in cwd.
echo:
echo If input is empty, current working directory (cwd)
echo will be considered.
exit /b 1
)
) else (
set /a "filecount=0"
for /f "tokens=* delims=" %%f in ('dir /b "%~dp0"') do (
echo %%f
set /a "filecount+=1"
)
echo:
echo In "%~dp0" found !filecount! file^(s^).
)
endlocal
If you want it recursive call it as progname.bat /r [foldname]:
setlocal enabledelayedexpansion
rem Put it into a folder that is in ENV PATH variable.
rem So, you can call it from wherever you want.
if "%1"=="/r" shift
if not "%1"=="" (
if exist "%~dpn1" (
set /a "filecount=0"
set /a "totalcount=0"
set "oldroot=%~dpn1"
for /f "tokens=* delims=" %%f in ('dir /b /s "!cd!"') do (
if not "%%~dpf"=="!oldroot!" (
echo:
echo In "!oldroot!" found !filecount! file^(s^).
echo:
set /a "filecount=0"
set "oldroot=%%~dpf"
)
echo --- %%f
set /a "filecount+=1"
set /a "totalcount+=1"
)
echo:
echo In "%~dpn1" found !totalcount! file^(s^).
) else (
echo:
echo [ERROR] Invalid input. Please specify:
echo 1. A full path.
echo 2. A folder in cwd.
echo:
echo If input is empty, current working directory (cwd)
echo will be considered.
exit /b 1
)
) else (
set /a "filecount=0"
set /a "totalcount=0"
set "oldroot=!cd!"
for /f "tokens=* delims=" %%f in ('dir /b /s "!cd!"') do (
if not "%%~dpf"=="!oldroot!" (
echo:
echo In "!oldroot!" found !filecount! file^(s^).
echo:
set /a "filecount=0"
set "oldroot=%%~dpf"
)
echo --- %%f
set /a "filecount+=1"
set /a "totalcount+=1"
)
echo:
echo In "%~dp0" found !totalcount! file^(s^).
)
endlocal
Try it and see if it is what you expected.
Thank you for the help everybody, I've found the solution to the problem and it was very simple. All I needed to do was loop through %1\*.* instead of %1 itself.
#Echo off
if exist %1 (
for %%f in (%1\*.*) do (
echo %%f
)
) else (
echo "That directory does not exist."
)

find multiple files paths with single string

I tried to write a batch script that find all the paths of files that have the same name as the input string. right now it can find only the first file found, and i cant think of a way to make it list multiple files locations. I am not very experienced and I need some help.
this is part of the script code:
:start
cls
echo Enter file name with extension:
set /p filename=
echo Searching...
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%"') do (
set file=%%~nxb
set datapath=%%~dpb\
::the path of the file without the filename included "C:\folder\folder\"
set fullpath=%%b
::the path of the file with the filename included "C:\folder\folder\file"
goto break
)
)
:notfound
cls
echo Enter file name with extension:
echo %filename%
echo File Not Found!
ping localhost -n 4 >nul
goto start
:break
if "%datapath:~-1%"=="\" set datapath=%datapath:~,-1%
cls
echo 3 %filename% found
echo %fullpath1%
echo %fullpath2%
echo %fullpath3%
--- || ---
I want the script to search the computer and list every encountered files with the same name and I want to be able to put those files' paths into different variables.
For example, if readme.txt is the input, then I want the list of all the paths of all the files with that specific name (readme.txt) and I want to set variable for each path so I can use it after that.
input:
readme.txt
output:
3 files found
C:\folder\folder\readme.txt
C:\folder\folder\folder\readme.txt
D:\folder\readme.txt
#echo off
set filename=readme.txt
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%"') do (
echo you can do something here with %%~nxb in %%~dpb
echo full name: %%b
)
)
I see no need to set the filenames to variables, as you can process them inside your loop. But if you really need them (for some reason) in variables:
#echo off
setlocal enabledelayedexpansion
set filename=readme.txt
set count=0
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%" 2^>nul') do (
set /a count+=1
set _file[!count!]=%%b
)
)
set _file
You can try with this code :
#echo off
Title Searching for the path with the same file name
Mode con cols=80 lines=3 & Color 9E
SET /a Count=0
set /a cnt=1
set "FileName=Readme.txt"
set "Report=%~dp0Report.txt"
set "Folder2Copy=%~dp0Readme_Folder"
set "Result2Copy=%~dp0Result2Copy.txt
If exist %Folder2Copy% RD /S /Q %Folder2Copy%
If Exist %Report% Del %Report%
If Exist %Result2Copy% Del %Result2Copy%
echo(
Echo Searching for the path with the same file name
Rem Looking for fixed drives and store them into variables
SETLOCAL enabledelayedexpansion
For /f "skip=1" %%a IN ('wmic LOGICALDISK where driveType^=3 get deviceID') DO (
for /f "delims=" %%b in ("%%a") do (
SET /a "Count+=1"
set "Drive[!Count!]=%%b"
)
)
:Display
for /L %%i in (1,1,%Count%) do (
cls
Title Please wait a while ... Searching for "%FileName%" on "!Drive[%%i]!\"
echo(
echo Please wait a while ... Searching for "%FileName%" on "!Drive[%%i]!\"
Call :FindPathFile !Drive[%%i]!\ %FileName% >> %Report%
)
Start "" %Report%
Goto :AskQuestion
::***************************************************************************************
:FindPathFile <Location> <FileName>
Where.exe /r %1 %2
Goto :eof
::***************************************************************************************
:AskQuestion
cls & Mode con cols=100 lines=5
echo(
echo Did you want to make copy of all files found as name "%FileName%"
echo saved on "%Report%" ? (Y/N) ?
set /p "Input="
If /I "%INPUT%"=="Y" (
for /f "delims=" %%i in ('Type "%Report%"') do (
Call :MakeCopy "%%~i" "%Folder2Copy%\"
)
)
Call :Explorer "%Folder2Copy%\" & exit
If /I "%INPUT%"=="N" (
Exit
)
Goto :eof
::***************************************************************************************
:MakeCopy <Source> <Target>
If Not Exist "%~2\" MD "%~2\" (
if not exist "%2\%~n1" (
echo copying "%~1" to "%~2"
copy /N /B "%~1" "%~2" >>%Result2Copy% 2>&1
) else (
call :loop "%~1" "%~2"
)
)
::***************************************************************************************
:loop
set "fname=%2\%~n1(%cnt%)%~x1"
if exist "%fname%" set /a cnt+=1 && goto :loop
copy "%~1" "%fname%"
exit /b
::***************************************************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::***************************************************************************************

Find string in multiple .txt files

I have a folder with many .txt files. I would like to find string "X" in all of these files then I would like to copy the found strings into .txt files into a different folder.
So far I have tried :
#echo on
findstr /m "X" "%userprofile%\Desktop\New_Folder\New_Folder\*.txt"
if %errorlevel%==0 do (
for %%c in (*.txt) do (
type %%c >> "%UserProfile%\Desktop\New_Folder\%%~nc.txt"
pause
I do not understand the output %%~nc.txt part it's suppost to copy the changed .txt files to a new folder with the same name.
I would like to point out that string "X" is found in different places in the .txt file.
This batch file can did the trick (-_°)
So, just give a try : ScanfilesWordSearch_X.bat
#ECHO OFF
::******************************************************************************************
Title Scan a folder and store all files names in an array variables
SET "ROOT=%userprofile%\Desktop"
Set "NewFolder2Copy=%userprofile%\Desktop\NewCopyTxtFiles"
SET "EXT=txt"
SET "Count=0"
Set "LogFile=%~dp0%~n0.txt"
set "Word2Search=X"
SETLOCAL enabledelayedexpansion
REM Iterates throw the files on this current folder and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
For %%a in (%EXT%) Do (
Call :Scanning "%Word2Search%" "*.%%a"
FOR /f "delims=" %%f IN ('dir /b /s "%ROOT%\*.%%a"') DO (
( find /I "%Word2Search%" "%%f" >nul 2>&1 ) && (
SET /a "Count+=1"
set "list[!Count!]=%%~nxf"
set "listpath[!Count!]=%%~dpFf"
)
) || (
( Call :Scanning "%Word2Search%" "%%~nxf")
)
)
::***************************************************************
:Display_Results
cls & color 0B
echo wscript.echo Len("%ROOT%"^) + 20 >"%tmp%\length.vbs"
for /f %%a in ('Cscript /nologo "%tmp%\length.vbs"') do ( set "cols=%%a")
If %cols% LSS 50 set /a cols=%cols% + 20
set /a lines=%Count% + 10
Mode con cols=%cols% lines=%lines%
ECHO **********************************************************
ECHO Folder:"%ROOT%"
ECHO **********************************************************
If Exist "%LogFile%" Del "%LogFile%"
rem Display array elements and save results into the LogFile
for /L %%i in (1,1,%Count%) do (
echo [%%i] : !list[%%i]!
echo [%%i] : !list[%%i]! -- "!listpath[%%i]!" >> "%LogFile%"
)
(
ECHO.
ECHO Total of [%EXT%] files(s^) : %Count% file(s^) that contains the string "%Word2Search%"
)>> "%LogFile%"
ECHO(
ECHO Total of [%EXT%] files(s) : %Count% file(s)
echo(
echo Type the number of file that you want to explore
echo(
echo To save those files just hit 'S'
set /p "Input="
For /L %%i in (1,1,%Count%) Do (
If "%INPUT%" EQU "%%i" (
Call :Explorer "!listpath[%%i]!"
)
IF /I "%INPUT%"=="S" (
Call :CopyFiles
)
)
Goto:Display_Results
::**************************************************************
:Scanning <Word> <file>
mode con cols=75 lines=3
Cls & Color 0E
echo(
echo Scanning for the string "%~1" on "%~2" ...
goto :eof
::*************************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::*************************************************************
:MakeCopy <Source> <Target>
If Not Exist "%~2\" MD "%~2\"
Copy /Y "%~1" "%~2\"
goto :eof
::*************************************************************
:CopyFiles
cls
mode con cols=80 lines=20
for /L %%i in (1,1,%Count%) do (
echo Copying "!list[%%i]!" "%NewFolder2Copy%\"
Call :MakeCopy "!listpath[%%i]!" "%NewFolder2Copy%">nul 2>&1
)
Call :Explorer "%NewFolder2Copy%\"
Goto:Display_Results
::*************************************************************
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "mystring=x"
FOR %%a IN ("%sourcedir%\*.txt") DO FINDSTR "%mystring%" "%%a">nul&IF NOT ERRORLEVEL 1 FINDSTR "%mystring%" "%%a">"%destdir%\%%~nxa"
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances and set mystring appropriately, noting that you may have to adjust the findstr switches to accomodate case, literal and space-in-target-string.
Naturally, you could code sourcedir etc. directly as literals, but doing it this way means that the relevant strings need only be changed in one place.
You are close, but checking the ErrorLevel of findstr does not make sense here as this reflects the overall result, that is, ErrorLevel is set to 0 in case any of the files contain the search string.
I would parse the output of findstr /M using a for /F loop and copy the returned files in the body:
for /F "eol=| delims=" %%F in ('
findstr /M /I /C:"X" "%USERPROFILE%\Desktop\New_Folder\New_Folder\*.txt"
') do (
copy "%%F" "%USERPROFILE%\Desktop\New_Folder\"
)
This copies all those files which contain the literal search string (in a case-insensitive manner).

Windows batch file to list all duplicates (and the original file) in tree and sort them

I have to check a tree for duplicating files and write all of them to List.txt file.
But my script seems to skip one of the file locations in each group. (For example, if there are 4 duplicating files, only 3 of them appear in the list.)
If I'm not mistaken, it's the location of the "previousFile" of the last comparison that is missing. How do I write it to the list, too?
Also, how can I group paths in the List.txt by the filename so that it looks something like this:
File fileNameA.txt :
C:\path1\fileNameA.txt
C:\path2\fileNameA.txt
C:\path3\fileNameA.txt
File fileNameB.txt :
C:\path1\fileNameB.txt
C:\path2\fileNameB.txt
C:\path3\fileNameB.txt
C:\path4\fileNameB.txt
File fileNameC.txt :
C:\path1\fileNameC.txt
C:\path2\fileNameC.txt
...
?
That's my script so far:
#echo off
setlocal disableDelayedExpansion
set root=%1
IF EXIST List.txt del /F List.txt
set "prevTest=none"
set "prevFile=none"
for /f "tokens=1-3 delims=:" %%A in (
'"(for /r "%root%" %%F in (*) do #echo %%~zF:%%~fF:)|sort"'
) do (
set "currentTest=%%A"
set "currentFile=%%B:%%C"
setlocal enableDelayedExpansion
set "match="
if !currentTest! equ !previousTest! fc /b "!previousFile!" "!currentFile!" >nul && set match=1
if defined match (
echo File "!currentFile!" >> List.txt
endlocal
) else (
endlocal
set "previousTest=%%A"
set "previousFile=%%B:%%C"
)
)
You need to count matches and add echo previous filename to echo current one in case of the first match.
Note '"(for /r "%root%" %%F in (*) do #echo(%%~nxF?%%~zF?%%~fF?)|sort"' changes:
used ? (question mark) as a delimiter: reserved character by Naming Files, Paths, and Namespaces
added %%~nxF? prefix to sort output properly by file names even in my sloppy test folder structure, see sample output below.
This output shows than even cmd poisonous characters (like &, %, ! etc.) in file names are handled properly with DisableDelayedExpansion kept.
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "root=%~1"
if not defined root set "root=%CD%"
set "previousTest="
set "previousFile="
set "previousName="
set "match=0"
for /f "tokens=1-3 delims=?" %%A in (
'"(for /r "%root%" %%F in (*) do #echo(%%~nxF?%%~zF?%%~fF?x)|sort"'
) do (
set "currentName=%%A"
set "currentTest=%%B"
set "currentFile=%%C"
Call :CompareFiles
)
ENDLOCAL
goto :eof
:CompareFiles
if /I "%currentName%" equ "%previousName%" ( set /A "match+=1" ) else ( set "match=0" )
if %match% GEQ 1 (
if %match% EQU 1 echo FILE "%previousFile%" %previousTest%
echo "%currentFile%" %currentTest%
) else (
set "previousName=%currentName%"
set "previousTest=%currentTest%"
set "previousFile=%currentFile%"
)
goto :eof
Above script lists all files of duplicated names regardless of their size and content. Sample output:
FILE "d:\bat\cliPars\cliParser.bat" 1078
"d:\bat\files\cliparser.bat" 12303
"d:\bat\Unusual Names\cliparser.bat" 12405
"d:\bat\cliparser.bat" 335
FILE "d:\bat\Stack33721424\BÄaá^ cčD%OS%Ď%%OS%%(%1!)&°~%%G!^%~2.foo~bar.txt" 120
"d:\bat\Unusual Names\BÄaá^ cčD%OS%Ď%%OS%%(%1!)&°~%%G!^%~2.foo~bar.txt" 120
To list all files of duplicated names with the same size but regardless of their content:
:CompareFiles
REM if /I "%currentName%" equ "%previousName%" (
if /I "%currentTest%%currentName%" equ "%previousTest%%previousName%" (
set /A "match+=1"
REM fc /b "%previousFile%" "%currentFile%" >nul && set /A "match+=1"
) else ( set "match=0" )
To list all files of duplicated names with the same size and binary content:
:CompareFiles
REM if /I "%currentName%" equ "%previousName%" (
if /I "%currentTest%%currentName%" equ "%previousTest%%previousName%" (
REM set /A "match+=1"
fc /b "%previousFile%" "%currentFile%" >nul && set /A "match+=1"
) else ( set "match=0" )
Edit If the name of the file doesn't matter (only its contents), you could apply next changes in FOR loop and in :CompareFiles subroutine:
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "root=%~1"
if not defined root set "root=%CD%"
set "previousTest="
set "previousFile="
set "match=0"
for /f "tokens=1-2 delims=?" %%A in (
'"(for /r "%root%" %%F in (*) do #echo(%%~zF?%%~fF?)|sort"'
) do (
set "currentTest=%%A"
set "currentFile=%%B"
rem optional: skip all files of zero length
if %%A GTR 0 Call :CompareFiles
)
ENDLOCAL
goto :eof
:CompareFiles
if /I "%currentTest%" equ "%previousTest%" (
fc /b "%previousFile%" "%currentFile%" >nul && set /A "match+=1"
) else ( set "match=0" )
if %match% GEQ 1 (
if %match% EQU 1 echo FILE "%previousFile%" %previousTest%
echo "%currentFile%" %currentTest%
) else (
set "previousTest=%currentTest%"
set "previousFile=%currentFile%"
)
goto :eof

Windows batch script issue

I am having an issue with the following Windows batch script. I have multiple XML files in the %indir% that I want to import one at a time and email the report. Basically the section starting with "if /I %v_continue% == y" is not executing as expected. I did some debugging step by step with echo on, and it goes through the script till the %BLAT% command without executing any of the steps, and then it starts execution with the first "copy %script_path%.....". It executes the import.exe correctly, but then nothing gets assigned to %subj% and subsequently the %BLAT% command fails. Any advice?
Thanks!
#echo off
set environment=%1
set domain=%2
if [%environment%] == [] goto :endofscript
rem - Get the script path
set script_path=%~dp0
rem - Get the script name without the extension
set script_name=%~n0
rem - Get the script name with the extension
rem set script_name=%~nx0
rem - get the script extension
set script_ext=%~x0
rem - Set environment variables
call %script_path%\setenv.cmd
set cnt=0
set filemask=*.xml
for /f %%a in ('dir /b /a-d %indir%\%filemask%') do call :procfile %%a
goto :EOF
:procfile
set impfile=%1
set v_continue=n
set emailyn=y
set trset=%impfile:~0,3%
set /A cnt + = 1
if 1%cnt% lss 100 set cnt=0%cnt%
if %trset% == RCT (
set "subtxt=Receipt Confirmation"
set v_continue=y
)
if %trset% == SHP (
set "subtxt=Shipment Confirmation"
set v_continue=y
setlocal EnableDelayedExpansion
set MOFound=
for /f "tokens=3 delims= " %%f in ('find /i /c "<RefID>MO-ORD</RefID>" %indir%\%impfile%') do (set MOFound=%%f)
if !MOFound! GTR 0 (
copy %indir%\%impfile% %inarchdir%
move %indir%\%impfile% %S_INDIR%\FX%dttmstamp%%cnt%.xml 2>NUL
goto :EOF
)
endlocal
)
if /I %v_continue% == y (
copy %script_path%\%script_name%.dat %infile%
cscript %REPLACEVBS% %infile% "DOMAIN" "%domain%" 1>NUL 2>&1
cd /d %rptdir%
%DLC%\bin\import.exe -b -T d:\tmp -p %pfile%
rem - Check for errors
find /i /c "ERROR:" %rptfile% > NUL
if %ERRORLEVEL% NEQ 0 (
set "subj=SUCCESS: %subtxt% Import Report (%environment%/%domain%)"
set emailyn=y
) else (
set "subj=ERROR: %subtxt% Import Report (%environment%/%domain%)"
set emailyn=y
)
move %rptfile% %logdir%\%script_name%_%datestamp%_%cnt%.prn 2>NUL
move %outfile% %logdir%\%script_name%_%datestamp%_%cnt%.out 2>NUL
if /I %emailyn% == y (
echo Report location: %logdir%\%script_name%_%datestamp%_%cnt%.prn > %msgfile%
%BLAT% %msgfile% -server abc-com.mail.protection.outlook.com -f donotreply#abc.com -s "%subj%" -t %INBEMAIL% -attachi %logdir%\%script_name%_%datestamp%_%cnt%.prn
)
)
del /f /q %infile%
del /f /q %pfile%
del /f /q %msgfile%
:delfiles
rem - Delete log files that are older than 10 days.
PushD "%logdir%" && (
forfiles /M %script_name%_*.prn /D -10 /C "CMD /C del /f /q #PATH" 2>NUL
) & PopD
:endofscript
exit /B

Resources