Change Directory of Batch File to the batch file's location - windows

Weekly, I have to update our computers with publications for our aircraft. I have streamlined the process by creating a batch file that deletes the old publications automatically and opens the folder where they are stored so I don't have to dig for it. The location where the publications are stored each week is the same. My batch file looks like below...
del /s /f "C:\Users\Public\Desktop\PubFolder\Pub.pdf"
So basically all I have to do is copy the PubFolder from my USB drive to the Public Desktop after I have ran the batch file to delete all of the publications.
If all of our computers were exactly the same, this would be an easy fix because I could write in the batch file
xcopy /y D:\PubFolder" "C:\Users\Public\Desktop\PubFolder"
and the script would do all of the work for me. My issue is, a lot of the computers have different software installed on them which require partitions in the HDD. Some of them have 3, some 2, some 1.
Basically what I'm needing is when I run the batch file from the USB, it uses the location of the batch file as the directory so I can copy from there.

A cmd script (.bat file) can reference its own directory with %~dp0
See the details using FOR /?
While you are at it, some additional error checking might make some situations easier to recover from.
SETLOCAL
SET "EXITCODE=0"
SET "USERDIR=%PUBLIC%\Desktop\PubFolder"
IF NOT EXIST "%USERDIR%" (
ECHO ERROR: The user publication directory "%USERDIR%" does not exist.
SET EXITCODE=4
GOTO TheEnd
)
IF EXIST "%USERDIR%\Pub.pdf" (DEL "%USERDIR%\Pub.pdf")
xcopy /y %~dp0PubFolder" "%USERDIR%"
SET "EXITCODE=%ERRORLEVEL%"
IF %EXITCODE% NEQ 0 (
ECHO ERROR: Failed to copy from "%~dp0" to "%USERDIR%"
SET EXITCODE=5
GOTO TheEnd
)
:TheEnd
EXIT /B %EXITCODE%

#setlocal
REM If you have pre-Vista machines, uncomment the folowing line:
REM #if not defined PUBLIC set PUBLIC=%SYSTEMDRIVE%\Users\Public%
#xcopy /y %~d0\PubFolder %PUBLIC%\Desktop\PubFolder

Related

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.

Windows batch file - process one file at a time

Odd question - but it's driving me a bit crazy. I have a directory where multiple files can be dumped via FTP, then I need to process them one at time. So basically in this directory I could have 1.txt, 2.txt, 3.txt etc then I need to:
copy the file to an archive (if exist copy to archive)
move the file to one specific filename one at a time - data.txt <--- this is what's getting me
run a command on a legacy backend system client using that specific filename (data.txt)
run another command on legacy client using data.txt
delete data.txt
Move on to the next file and repeat
So far I've tried several methods of do loops without any luck - they all get hung up on trying to rename multiple files into one file, and that just kills me. I'd long ago since given up on batch files but annoyingly, this application has to use windows, and Server 2003 to boot.
EDIT: Here's what I've tried-
This works to do one file at a time:
if exist c:\jail\ftp*.txt copy c:\jail\ftp*.txt w:\scans\archive*.txt
if exist c:\jail\ftp*.txt move c:\jail\ftp*.txt w:\data.txt
if exist w:\data.txt C:\temp\rmtcmdb.exe
if exist w:\data.txt del w:\data.txt
I've tried multiple for loops without success, here is the latest (NOTE - I'm just trying to get past the move stage on this one, once I'm done with that I'll add in the rest):
setlocal ENABLEDELAYEDEXPANSION
FOR /f %%a IN ("c:\jail\ftp\") DO (
CALL SET /A x = !x! +1
if !x! == 1 (
CALL copy %%a w:\scans\archive*.txt
CALL move %%a w:\data.txt
)
)
I've also tried some very basic for loops, and again - nothing is getting past the move stage.
Any suggestions?
#echo off
setlocal enableextensions
for %%a in ("c:\jail\ftp*.txt") do (
set "fileName=%%~na"
setlocal enabledelayedexpansion
copy "%%~fa" "w:\scans\!fileName:*ftp=archive!%%~xa"
endlocal
move /y "%%~fa" "w:\data.txt"
start "" /wait "c:\temp\rmtcmdb.exe"
if exist "w:\data.txt" del /s "w:\data.txt" >nul 2>nul
)

BATCH FILE - IF Exists & Output Error

INFO: assets.txt contains a list of cpu names which I can connect to over the network.
I need to copy this new .exe to well over 200+ computers and figured i could use the c$ admin share. This is really the only way I can do this without going to workstations individually or remoting in one by one.
This script works without the 'if exists' however I need to check if the directory exists before attempting the copy. I don't understand why it isn't working. I am also running this script using my domain administrative account.
#echo off
REM Pull Computer Asset Tags from file
for /F "tokens=*" %%A in (assets.txt) do (
echo Start Processing %%A
REM Temporarily set file path for existence check
set file=\\%%A\C$\Program Files\Intouch2\Intouch2ca.exe
if EXIST "%file%" (
REM Rename old .exe
ren "\\%%A\C$\Program Files\Intouch2\Intouch2ca.exe" "Intouch2ca.bak"
REM copy new .exe from server to cpu asset
xcopy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" /Y
echo END Processing %%A
echo.
echo ------------------------------------------------------------
echo.
)
)
I also haven't been able to get the error output to a log file.
I have tried this but it isnt exactly what I would like.
xcopy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" /Y 1>>errors.log 2>&1
How can I pretty that up so it only shows errors and lists the %%A where the error occured?
Thank you all in advance for your time.
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.
Hence, in your case, file is being changed within the block, so the value cmd uses is its initial value when the entire for is parsed.
Solution 1: use \\%%A\C$\Program Files\Intouch2\Intouch2ca.exe in place of %file%
Solution 2: start your batch with setlocal enabledelayedexpansion on a separate line after the #echo off, then use !file! in place of %var%
Solution 3: call an internal routine to use the mofified value as %file%
Solution 4: Create the directory regardless. MD newname 2>nul will silently create a new directory if it doesn't already exist
An error on a copy will set an errorlevel and you can write a custom error message.
copy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" >nul 2>&1
if errorlevel 1 >> errors.txt echo "Error in %%A"

Batch file to create subfolder in other subfolders, but only at top level

I have a similar problem to this post, but I couldn't get the solution to work (I'm a total novice).
I have a set of folders on a network drive, each folder named after a manager (e.g. \sfnetfile\DEPT\HR_Manager\Manager, Test and \sfnetfile\DEPT\HR_Manager\Manager, Test 2). I am trying to get a folder/subfolder combo created in each manager folder of 2013\Variable. In some cases managers already have a 2013 subfolder, but not the Variable sub-subfolder (excuse the silly terminology).
I also want to prevent the batch file from creating the 2013\Variable folder in existing other subfolders within each manager folders (so I don't want it, for example, creating another level down: \sfnetfile\DEPT\HR_Manager\Manager, Test 2\2012\2013\Variable.
Here is my code:
FOR /d %A IN (\sfnetfile\DEPT\HR_Manager*) DO mkdir "%A"\2013\Variable
Something like this should do:
#echo off
for /d %%d in (\\sfnetfile\DEPT\HR_Manager\*) do md "%%~d\2013\Variable" 2>nul
assuming that sfnetfile is the name of a remote server and DEPT is a shared folder on that server. If sfnetfile is a top level folder on a mapped network drive, change that to:
#echo off
for /d %%d in (X:\sfnetfile\DEPT\HR_Manager\*) do md "%%~d\2013\Variable" 2>nul
where X: is the drive letter of the network drive.
Edit: As #dbenham correctly mentions, redirecting error output (to suppress error messages for existing leaf folders) will also suppress any other error message. A more sophisticated approach would check if the folder doesn't already exist and only then create it:
#echo off
setlocal EnableDelayedExpansion
for /d %%d in (\\sfnetfile\DEPT\HR_Manager\*) do (
set "folder=%%~d\2013\Variable"
if exist "!folder!" (
if not exist "!folder!\" echo "!folder!" exists as a file! 1>&2
) else (
mkdir "!folder!"
)
)

How to copy a location to a batch file from a file that is dragged and dropped to open the batch file

So I've been trying to create a batch file for a piece of software called DiscEX the software requires command line use from cmd.exe windows xp or higher the way it's initiated is like this discex (any arguments needed) location of iso file.
Now I can get the software to run using the batch file but I can't seem to figure out how to copy the target location of a file that was dragged onto it to open the batch file up
Here is what the batch file in notepad looks like.
#echo off
echo Welcome to AutoDiscEx
pause
C:\windows\system32\discex
pause
also I need to be able to start in the working directory of a portable hard drive.
All you need to do is
C:\windows\system32\discex "%1"
to get a file path argument passed into the batch
If the batch file is in the working directory already, put
cd /d %~dp0 in the batch after #echo off
If you want to determine what drive is the external usb drive, use
#echo off
setlocal
set wmi='wmic logicaldisk where "volumeserialnumber='32A78F3B'" get caption'
for /f "skip=1 delims=" %%A in (%wmi%) do (
for /f "tokens=1 delims=:" %%B in ("%%A") do (set drive=%%B)
)
echo %drive%
where volumeserialnumber is the output from vol [driveletter of USB drive:] with the - removed.
When you drag a file on a batch file, the full file path is available in the first argument (%1) of the batch file. If you need this argument to be fed to the discex application as its first argument, you can do:
#echo off
echo Welcome to AutoDiscEx
pause
C:\windows\system32\discex %1
pause

Resources