Drag and drop to batch file from UNC - how to capture %cd% - windows

I have a batch file:
#ECHO OFF
Set dd=%DATE:~0,2%
Set mm=%DATE:~3,2%
Set yyyy=%DATE:~6,4%
Set hh=%TIME:~0,2%
Set ii=%TIME:~3,2%
Set ss=%TIME:~6,2%
Set zipFileHandle=%yyyy%-%mm%-%dd%-%hh%-%ii%-%ss%
Set files=%*
%~dp0\7za a -t7z %cd%\%zipFileHandle%.7z %files%
When I drop a group of files and/or directories on it, it compresses them into a dated .7z file in the root folder they all came from.
The problem is that if I drop network files, with a path starting with \\, the batch file changes the value of the save directory to C:\Windows.
How can I get the value of %cd% before cmd changes it to the system root?
If that's not possible, is it possible to get the common root folder from the variable %files%?

You should get next message:
'\\computer\path'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
So you could use next:
%~dp07za a -t7z %~dp1%zipFileHandle%.7z %files%
Note that \ backslash could be omitted using %~dp0 and %~dp1 as the ~dp modifier expands a %variable to a Path only including a trailing \ backslash.
And if source folder name contains spaces, use quoted target file name rather:
%~dp07za a -t7z "%~dp1%zipFileHandle%.7z" %files%

You could pushd %~dp1 before calling 7za. That temporarily maps the UNC path of the 1st dragged-and-dropped file as a network drive letter and changes directory to it. The mapping disappears as soon as the script exists.
Additionally, 7za has exit codes you might make use of for fault tolerance.
#echo off
setlocal
for /f "tokens=2 delims=.=" %%I in (
'wmic os get localdatetime /format:list ^| find "="'
) do set "t=%%I"
set "handle=%t:~0,4%-%t:~4,2%-%t:~6,2%_%t:~8,2%-%t:~10,2%-%t:~12,2%"
pushd "%~dp1"
"%~dp0\7za" a -t7z "%handle%.7z" %* || (
if ERRORLEVEL 2 (
echo Zipping failed.
pause
) else (
echo Zipping completed with errors, possibly because a file is locked by another process.
pause
)
)

Related

loop through a folder with special characters in the folder name

I'm trying to write a batch file to move files from a folder into another folder. The folder has a special character in the name. I can't change that name.
Here is my script
set "MM=%Date:~4,2%"
set "DD=%Date:~7,2%"
set "thisDate=%MM%%DD%"
set baseDir="T:\R ^& D files received"
set backupDir=%baseDir%\2022\%thisDate%
if not exist "%backupDir%\NUL" mkdir "%backupDir%"
for %%f in ("%baseDir%\*.pdf") do (
echo %%f
move %%f "%backupDir%\%%f")
This is not working. I get
R
&
D
files
received\*.pdf
No file is moved.
Any idea or help is appreciated.
#ECHO OFF
SETLOCAL
SET "thisdate=0419"
set "baseDir=U:\R & D files received"
set "backupDir=%baseDir%\2022\%thisDate%"
if not exist "%backupDir%\NUL" mkdir "%backupDir%"
for %%f in ("%baseDir%\*.pdf") do (
echo "%%f"
move "%%f" "%backupDir%\%%~nxf" >nul
)
DIR /s "%basedir%"
GOTO :EOF
Intriguingly. you've used the set "var=value" format for setting thisdate but not for the directory names. I've used a constant for thisdate as I use a YYYYMMDD date format.
Also, my test drive is U:, not T:.
Tips : Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, space or quotes - build pathnames from the elements - counterintuitively, it is likely to make the process easier.
Your for %%f resolved to for %%f in (""T:\R ^& D files received"\*.pdf") do ( hence the strange result.
Note that %%f contains the full pathname to the .pdf files - which includes spaces. Hence you need to "quote the sourcefile name" and use just the name and extension of that file (%%~nxf) concatenated onto the backupdirectoryname string with separator - all of which again contains a space and hence needs to be quoted.
>nul appended to suppress 1 file(s) moved messages.

How to include system variable in batch file inside FOR loop ? also escaping the ! and % sign inside variable?

lets say i have a list file contains folder names that i want to delete periodically based on a list,
currently using this batch file which don't work as i expected :
setlocal enabledelayedexpansion
for /F "tokens=2* delims==" %%x in ('findstr/brc:"foldertodelete" garbagefolderlist.txt') do (
set "foldertodelete=%%x"
set foldertodelete=!foldertodelete:"=!
set foldertodelete=!foldertodelete:%%=^!!"
echo !foldertodelete!
if exist !foldertodelete! (
echo deleting !foldertodelete!
rmdir /s /q !foldertodelete!>nul
)
)
endlocal
inside garbagefolderlist.txt :
foldertodelete="%programfiles%\blablabla"
fodlertodelete=%systemroot%\blablabla
foldertodelete="C:\Temp"
foldertodelete=D:\Temporary files\here
notes about the list file (garbagefolderlist.txt) :
1. folder names may contains double quotes or not, so i want to dynamically eliminate the double quotes inside batch file
2. folder names may be plain or using system variable or not like %systemroot%, etc
3. folder names may contains spaces
If all you want to do is delete the folders listed in that text file you only need one single line of code. You need to use the CALL command to get the double variable expansion that you require. You don't even need delayed expansion at all.
for /F "tokens=2* delims==" %%x in ('findstr /bc:"foldertodelete" garbagefolderlist.txt') do call rmdir /s /q "%%~x" 2>nul
Here is the execution of your script on my system. I created a folder in Program Files and I also have a Temp folder on the C: drive. The line in your file with %systemroot% will not be chosen because you have a typo on that line. So the script will only attempt to process three lines from your input example.
I have added the echo to the code and removed the error dump to nul so that you can see all the output.
#echo off
for /F "tokens=2* delims==" %%x in ('findstr /bc:"foldertodelete" garbagefolderlist.txt') do (
call echo %%~x
call rmdir /s /q "%%~x"
)
And here is the output of that code.
C:\BatchFiles\SO\71120676>so.bat
C:\Program Files\blablabla
Access is denied.
C:\Temp
D:\Temporary files\here
The system cannot find the path specified.
So lets break down that output.
You can see that the %programfiles% variable is expanded as it echo's the folder name correctly but the folder cannot be deleted because I am not running from an elevated cmd prompt as Administrator. So that folder cannot be deleted.
The temp folder displays correctly and is deleted.
The last directory does not exist on my system as I don't have a D: drive so the system reports that it cannot find the path. If standard error was still being redirected to the NUL device you would not see the error which is why I don't bother with checking if a folder exists before I delete it.

How do I get a relative path out of a windows batch file using echo?

How do I get relative directories / partial paths to display as echo output from a windows .bat file?
How to split the filename from a full path in batch?
Talks about everything but.
I've found drive letters, filenames, extensions, shortened (8.3) names, and full paths - but no relative paths.
I'm running a recursive FOR /R loop; which traverses sub-directories. I would like something - that doesn't have twenty characters of useless path info - that tells me which directory each duplicate file lives in... without hardcoding the .bat file to live in a certain directory/path?
Maybe a solution would be to measure the length of the script's path and cut that off of the front of the full path? But I don't know how to manipulate that.
Script could be in many locations:
F:\a.bat<BR>
F:\Dir1\fileA.txt<BR>
F:\Dir20\fileA.txt
C:\Users\Longusername\Desktop\Container\a.bat<BR>
C:\Users\Longusername\Desktop\Container\Dir1\fileA<BR>
C:\Users\Longusername\Desktop\Container\Dir20\fileA
And right now the only options I have for output are (%%~nxG):
fileA.txt
fileA.txt
Which doesn't tell me which directory each file is in...or (%%~pnxG)
\Users\Longusername\Desktop\Container\Dir1\fileA.txt
\Users\Longusername\Desktop\Container\Dir20\fileA.txt
What I'd like, from any location:
\Dir1\fileA.txt
\Dir20\fileA.txt
Could be missing the leading \, but that's negligible. Other options than echo are permissible if they'll work on most window machines. They may lead to more questions, though - as I've figured out my other pieces with echo.
quite easy, if you think about it: just remove the current directory path (%cd%):
#echo off
setlocal enabledelayedexpansion
for /r %%a in (*.txt) do (
set "x=%%a"
echo with \: !x:%cd%\=\!
echo without \: !x:%cd%\=!
)
By the way: \folder\file always refers to the root of the drive (x:\folder\file), so it's not exactly a relative path.
This is similar to the already accepted answer, but with delayed expansion enabled only where needed. This should correctly output filenames containing ! characters.
#Echo Off
SetLocal DisableDelayedExpansion
Set "TopLevel=C:\Users\LongUserName"
For /R "%TopLevel%" %%A In ("*.txt") Do (
Set "_=%%A"
SetLocal EnableDelayedExpansion
Echo=!_:*%TopLevel%=!
EndLocal
)
Pause
You could also use Set "TopLevel=%~dp0", (the running script's directory) or Set "TopLevel=%~dp0..", (the running script's parent directory)
One potential benefit of the above method is that you can also use a location relative to the current directory for the value of %TopLevel% too, (in this case, based upon the initial example, the current directory would be C:\Users):
Set "TopLevel=LongUserName"
Although this would only work correctly if LongUserName didn't already exist as content of the path earlier in the tree.
You could use xcopy together with its /S (include sub-directories) and /L (list but do not copy) options since it returns relative paths then, so you do not have to do any string manipulation, which might sometimes be a bit dangerous, particularly when the current directory is the root of a drive:
xcopy /L /S /I /Y /R ".\*.txt" "\" | find ".\"
The appended find command constitutes a filter that removes the summary line # File(s) from the output.
To capture the output of the aforementioned command line just use a for /F loop:
for /F "delims=" %%I in ('
xcopy /L /S /I /Y /R ".\*.txt" "\" ^| find ".\"
') do (
rem // Do something with each item:
echo/%%I
)

How do you loop inside sub directories in windows, and repeat command using windows batch scripting

I am on Windows 10. I have a folder with sub folder. All subfolders have "Subs" folder inside them. I want to loop through all subdirectories, goto Subs directory, unrar a file, Goto next subdirectory and repeat.
I tried below script but could not get to work.
#echo off
setlocal enableextensions enabledelayedexpansion
set "rootFolder=C:\Users\MNM\MAT"
echo ----------------------------------------------------------------------
for /d /r "%rootFolder%" %%a in (.) do (
set mypath=%cd%
#echo %mypath%
cd %%a
set mypath=%cd%
#echo %mypath%
cd Subs
set mypath=%cd%
#echo %mypath%
C:\Users\MNM\MAT\unrar e *subs.rar C:\Users\MNM\mat2\
cd C:\Users\MNM\MAT
)
This simple task can be done with just a single command line:
#echo off
for /R "%USERPROFILE%\MAT" %%I in ("*subs.rar") do "%USERPROFILE%\MAT\UnRAR.exe" x -c- -idcdp -y "%%I" "%USERPROFILE%\mat2\"
USERPROFILE is a predefined Windows Environment Variable which is on your computer for your user account defined with value C:\Users\MNM.
The command FOR searches in directory C:\Users\MNM\MAT and all its non hidden subdirectories because of /R for non hidden files matching the pattern *subs.rar. Each file name found is assigned with full path to loop variable I.
UnRAR is executed for each found RAR archive file for extracting the archive to directory C:\Users\MNM\mat2 with extracting also the directory structures inside the RAR archive file because of command x instead of e. Existing files in destination directory (tree) are automatically overwritten because of -y. The switches -c- and -idcdp are for displaying less information during extraction process.
For a brief description of used and additionally available switches of UnRAR run in command prompt window UnRAR without any parameter or with /? as parameter. A complete description of the commands and switches of UnRAR can be found in text file Rar.txt in program files folder of WinRAR if that shareware application is also installed and not just the freeware UnRAR.
It is absolutely not needed to change into the directory containing the RAR archive file on extracting all RAR archives into same destination directory as it can be seen here.
This is one possible way if I understood your folder structure correctly:
#echo off
set "Base=C:\Users\MNM\MAT"
echo ----------------------------------------------------------------------
for /F "delims=" %%A in (
'dir /B/S "%Base%\*subs.rar" ^| findstr /i "^%Base:\=\\%\\[^\\]*\\Subs\\[^\\]*subs.rar$"'
) do Echo "C:\Users\MNM\MAT\unrar.exe" e "%%~fA" "C:\Users\MNM\mat2\"
the for /f will parse the output of the dir and findstr
dir will iterate all *subs.rar in the tree starting from %Base%
the complex RegEx in findstr will filter the rar's to those in a folder subs in a subfolder of %Base%
as a backslash is an escape char in a RegEx, literal backslashes have to be doubled.
If the output looks ok remove the echo in the last line.
Just because recursing all subdirectories and extracting all *subs.rar files wasn't requested here's an example that is based upon my assumptions:
#ECHO OFF
SET "rootDir=%USERPROFILE%\MAT"
IF /I NOT "%CD%"=="%rootDir%" CD /D "%rootDir%"
FOR /D %%A IN (*
) DO IF EXIST "%%A\Subs\*subs.rar" UNRAR e "%%A\Subs\*subs.rar" mat2\

How to execute an application existing in each specific folder of a directory tree on a file in same folder?

I have some folders with different names. Each folder has a specific structure as listed below:
Folder1
Contents
x64
Folder1.aaxplugin
TransVST_Fixer.exe
Folder 2
Contents
x64
Folder 2.aaxplugin
TransVST_Fixer.exe
There are two files within each subfolder x64. One file has the same name as the folder two folder levels above. The other file is an .exe file whose name is the same in all folders.
Now I need to run file with file extension aaxplugin on each specific .exe file. It would be obviously very time consuming opening each and every single folder and drag & drop each file on .exe to run it on this file.
That's why I am trying to create a batch script to save some time.
I looked for solutions here on Stack Overflow. The only thing I have found so far was a user saying this: When I perform a drag & drop, the process 'fileprocessor.exe' is executed. When I try to launch this exe, though, CMD returns error ('not recognized or not batch file' stuff).
How can I do this?
UPDATE 12/22/2015
I used first a batch file with following line to copy the executable into x64 subfolder of Folder1.
for /d %%a in ("C:\Users\Davide\Desktop\test\Folder1\*") do ( copy "C:\Program Files\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%a\x64\" 2> nul )
After asking here, I tried the following script:
for /f "delims=" %%F in ('dir /b /s x64\*.aaxplugin') do "%%~dpFTransVST_Fixer.exe" "%%F"
Unfortunately, the output is as following
C:\Users\Davide\Desktop>for /F "delims=" %F in ('dir /b /s x64\*.aaxplugin') do "%~dpFTransVST_Fixer.exe" "%F"
The system cannot find the file specified.
Try the following batch code:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\Desktop\test" %%F in (*.aaxplugin) do (
set "FilePath=%%~dpF"
if not "!FilePath:\x64\=!" == "!FilePath!" "%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%F"
)
endlocal
The command FOR with option/R searches recursive in all directories of directory %USERPROFILE%\Desktop\test being expanded on your machine to C:\Users\Davide\Desktop for files with file extension aaxplugin. The loop variable F contains on each loop run the name of the found file with full path without surrounding double quotes.
The drive and path of each found file is assigned to environment variable FilePath.
Next a case-sensitive string comparison is done between file path with all occurrences of string \x64\ case-insensitive removed with unmodified file path.
Referencing value of environment variable FilePath must be done here using delayed expansion because being defined and evaluated within a block defined with ( ... ). Otherwise command processor would expand %FilePath% already on parsing the entire block resulting in a syntax error on execution because string substitution is not possible as no environment variable FilePath defined above body block of FOR loop.
The strings are not equal if path of file contains a folder with name x64. This means on provided folder structure that the file is in folder x64 and not somewhere else and therefore the application is executed next from its original location to fix the found *.aaxplugin file.
The line with IF is for the folder structure example:
if not "C:\Users\Davide\Desktop\test\Folder1\Contents" == "C:\Users\Davide\Desktop\test\Folder1\Contents\x64\"
if not "C:\Users\Davide\Desktop\test\Folder 2\Contents" == "C:\Users\Davide\Desktop\test\Folder 2\Contents\x64\"
So for both *.aaxplugin files the condition is true because the compared strings are not identical
Also possible would be:
#echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%F in ('dir /A-D /B /S "%USERPROFILE%\test\*.aaxplugin" 2^>nul') do (
set "FilePath=%%~dpF"
if not "!FilePath:\x64\=!" == "!FilePath!" "%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%F"
)
endlocal
But command DIR is not really necessary as it can be seen on first provided code.
But if the application TransVST_Fixer.exe for some unknown reason does its job right only with directory of file being also the current directory, the following batch code could be used instead of first code using the commands pushd and popd:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\test" %%F in (*.aaxplugin) do (
set "FilePath=%%~dpF"
echo !FilePath!
if /I "!FilePath:~-5!" == "\x64\" (
pushd "%%~dpF"
"%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%~nxF"
popd
)
)
endlocal
There is one more difference in comparison to first code. Now the last 5 characters of path of file are compared case-insensitive with the string \x64\. Therefore the file must be really inside a folder with name x64 or X64. A folder with name x64 or X64 anywhere else in path of file does not result anymore in a true state for the condition as in first two batch codes.
But if for some unknown reason it is really necessary to run the application in same folder as the found *.aaxplugin and the directory of the file must be the current directory, the following batch code could be used:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\test" %%# in (*.aaxplugin) do (
set "FilePath=%%~dp#"
if /I "!FilePath:~-5!" == "\x64\" (
pushd "%%~dp#"
"%%~dp#TransVST_Fixer.exe" "%%~nx#"
popd
)
)
endlocal
The path of the file referenced with %%~dpF always ends with a backslash which is the reason why there is no backslash left of TransVST_Fixer.exe (although command processor could handle also file with with two backslashes in path).
In batch code above character # is used as loop variable because %%~dp#TransVST_Fixer.exe is easier to read in comparison to %%~dpFTransVST_Fixer.exe. It is more clear for a human with using # as loop variable where the reference to loop variable ends and where name of application begins. For the command processor it would not make a difference if loop variable is # or upper case F.
A lower case f would work here also as loop variable, but is in general problematic as explained on Modify variable within loop of batch script.
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.
dir /?
echo /?
endlocal /?
for /?
if /?
popd /?
pushd /?
set /?
setlocal /?
Your question isn't quite clear, but it seems, something like this should work:
for /f "delims=" %%f in ('dir /b /s X64\*.ext') do "%%~dpfMyExe.exe" "%%f"
Maybe you have to change directory to each folder (depends on your .exe):
for /f "delims=" %%d in ('dir /B /ad') do (
pushd "%%d"
for /f "delims=" %%f in ('dir /b "contents\x64\*.ext"') do (
cd Contents\x64
MyExe.exe "%%f"
)
popd
)
Assuming:
The Directory structure is fixed and the files are indeed in a subfolder contents\X64\.
MyExe.exe is the same (name) in every folder.
There is only one file *.ext in every folder.
I'll give you the script I created for doing so, hope it works for you
for /d %%d IN (./*) do (cd "%%d/Contents/x64" & "../../../TransVST_Fixer.exe" "%%d" & cd "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins")
Please note that I placed the fixer inside the root folder so I just have to copy it once. You have to place it inside your root folder and execute it. What it does:
iterate over each folder
for each one it enters /Contents/x64, executes the fixer (wich is 3 levels above) and after that returns to the original folder.
If you have your plugins in a different folder, you just have to change this part replacing the path for the one you have your plugins in.
cd "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins"
REMEMBER to place the script on that folder. For this example I place my script on the folder "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins" and run it (as a .bat).
PS: the fixer will place the fixed plugins in "C:\Users\Public\modified" (just read the screen while executing, it gives you the new files path. If you want to move them to the right path, you can execute this from the new files path ("C:\Users\Public\modified")
for %%d IN (*.aaxplugin) do (mkdir "%%d_temp/Contents\x64" & move "%%d" "%%d_temp/Contents\x64/%%d" & rename "%%d_temp" "%%d")
with that, I iterate over every plugin and create a folder with the same name (I create _temp because of name colision, after moving the file I rename it to the correct one), also with the subfolder "/Contents/x64", and move the plugin inside. Once donde, you can just take the resulting folders and place them in their correct path.
Hope it works, for me it works like a charm.

Resources