Execute command in Windows batch file - windows

I have a file located on a share folder. I have to execute that file from the local PC. The name of the file changes every day, hence I should find the name first and then execute that .exe file.
Here is my Batch:
#echo off
set FILE =
FOR /F %%a IN ('dir /s/b') DO (
set FILE=%%a
)
start %FILE%
The last line does not execute the file. Why is that?

Does it have spaces in the path?
Try this:
START "" "%FILE%"
The "" signifies an empty window title. When you quote the filename you have to specify a title, otherwise START will treat your quoted file path as the title.

Related

Backup script - find file by pattern, read it's full name and pass to script

I'm trying to use 7-Zip for backup purposes.
I have already wrote script for full backup:
#echo off
set source="c:\Source"
set destination="C:\Dest"
set dd=%DATE:~0,2%
set mm=%DATE:~3,2%
set yyyy=%DATE:~6,4%
set curdate=%dd%-%mm%-%yyyy%
"C:\Program Files\7-Zip\7z.exe" a -tzip -ssw -mx6 -r0 %destination%\Full_%curdate%.zip %source%
The new script intended for incremental backup is started after the full backup is made. But I don't really get how to make my second script to read files from directory and look for the file staring like full_xx_xx_xxxx.zip and assign its filename to a variable and then pass it to the script for incremental backup.
I tried script below, but it's not working:
#echo off
set source="c:\Source"
set destination="c:\Dest"
set exten="Full_*.zip"
set passwd="NAS"
set dd=%DATE:~0,2%
set mm=%DATE:~3,2%
set yyyy=%DATE:~6,4%
set curdate=%dd%-%mm%-%yyyy%
for %%a in %exten do echo %%a
"C:\Program Files\7-Zip\7z.exe" u -tzip -ssw -r0 %destination%\%%a.zip -u- -up0q3x2z0!"%destination%\diff_%date%.zip" %source%
There are multiple mistakes in both scripts.
I recommend reading first How to set environment variables with spaces? and Why is no string output with 'echo %var%' after using 'set var = text' on command line?. The syntax set variable="value in quotes" is often not good because it assigns the string "value in quotes" with the double quotes and all trailing spaces/tabs which might exist also in batch file to the environment variable with name variable. This syntax is problematic on concatenating the string value of the environment variable with other strings as done in posted code with %destination% because of the " being now somewhere in middle of the final argument string instead of enclosing the entire argument string. Better is the syntax set "variable=value without or with spaces" with " left to variable name because of the double quotes are interpreted now as argument string separators and perhaps existing spaces/tabs on line after second " are ignored by Windows command processor.
The usage of dynamic environment variable DATE makes it possible to quickly get current locale date in a format usable for file/folder names. But it must be taken into account that the date format of value of DATE depends on region/country/locale set for the user account which is used on running the batch file. I suppose that echo %DATE% results in an output of a date in format DD.MM.YYYY and so the command lines using DATE are correct for you with your user account according to the configured country.
The FOR command line is completely wrong and results in an exit of batch file execution with an error message output by cmd.exe interpreting the batch file line by line. This error output can be seen on running the batch file from within a command prompt window instead of double clicking on the batch file. See debugging a batch file for details on how to debug a batch file to find syntax errors like this reported by Windows command processor during execution of a batch file.
So I suggest for the first batch file:
#echo off
set "Source=C:\Source"
set "Destination=C:\Dest"
set "CurrentDate=%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%"
"%ProgramFiles%\7-Zip\7z.exe" a -tzip -ssw -mx6 -r0 "%Destination%\Full_%CurrentDate%.zip" "%Source%"
The current locale date is assigned to the environment variable CurrentDate in format YYYY-MM-DD instead of DD-MM-YYYY. The date format YYYY-MM-DD is the international date format according to ISO 8601. It has one big advantage in comparison to all locale date formats in file names: The file names with date in format YYYY-MM-DD sorted alphabetically as usual are at the same time sorted chronological. That makes it much easier for people and scripts finding a specific file in a list of file names with date in file name.
I am not really sure what you want to do with the second batch file. So I can only suppose what you want to do and suggest for the second batch file:
#echo off
set "Source=C:\Source"
set "Destination=C:\Dest"
set "CurrentDate=%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%"
set "NamePattern=Full_*.zip"
for /F "skip=1 eol=| delims=" %%I in ('dir "%Destination%\%NamePattern%" /A-D /B /O-N 2^>nul') do (
"%ProgramFiles%\7-Zip\7z.exe" u -tzip -ssw -r0 "%Destination%\%%I" -u- -up0q3x2z0!"%Destination%\Diff_%CurrentDate%.zip" "%Source%"
goto Done
)
:Done
The FOR loop runs command DIR with using a separate command process started in background to get the list of Full_*.zip file names in destination directory sorted reverse by name which means the full backup ZIP file created today before with first batch file is at top on using date format YYYY-MM-DD and the previously created ZIP file from yesterday (or whenever the last but one full ZIP file was created) is output as second line.
FOR skips the first line with ZIP file name with current date and runs 7-Zip with previously created ZIP file (yesterday) to create the difference ZIP file. Then the FOR loop is exited without processing all other full ZIP files with a jump to the label below the FOR loop.
Both batch files together:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Source=C:\Source"
set "Destination=C:\Dest"
set "CurrentDate=%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%"
set "NamePattern=Full_*.zip"
rem Create full ZIP backup.
"%ProgramFiles%\7-Zip\7z.exe" a -tzip -ssw -mx6 -r0 "%Destination%\Full_%CurrentDate%.zip" "%Source%"
rem Create difference ZIP backup with files added/changed in source directory
rem in comparison to the files compressed into last but on full ZIP backup.
for /F "skip=1 eol=| delims=" %%I in ('dir "%Destination%\%NamePattern%" /A-D /B /O-N 2^>nul') do (
"%ProgramFiles%\7-Zip\7z.exe" u -tzip -ssw -r0 "%Destination%\%%I" -u- -up0q3x2z0!"%Destination%\Diff_%CurrentDate%.zip" "%Source%"
goto Done
)
:Done
endlocal
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 /?
rem /?
set /?
setlocal /?

Run Autocad exe and load script file error

This is My first post in here
I need a help for your side I have made a batch file for run autocad exe and load a script file but give error when I run the batch file
#echo off
set KEY_NAME=HKCU\Software\Laxman Enterprises\Xpresslisp Tools
set VALUE_NAME=installpath
set FN=loadload
set FE=scr
FOR /F "tokens=2*" %%A IN ('REG.exe query "%KEY_NAME%" /v "%VALUE_NAME%"') DO (set pInstallDir=%%B)
set approot=%pInstallDir:~0,-1%
echo %approot%\%FN%.%FE%
"C:\Program Files (x86)\AutoCAD 2002\acad.exe" /b %approot%\%FN%.%FE%
pause
Error: while running batch file autocad opens and in commandline the script file not loading "Xpresslisp.scr": Can't find file."
and bellow one is working
script file loading without getting error
#echo off
set path=%USERPROFILE%
set fol=Documents
set NAME=1
set SUFFIX=scr
"C:\Program Files (x86)\AutoCAD 2002\acad.exe" /b %path%\%fol%\%NAME%.%SUFFIX%
pause
Regarding your second question in the comments...
Bellow command will create the text file and write the first line to it e.g. "some text" like in the command below.
Echo some text > full_path_to_txt_file
Command below will append new text to same file.
Echo some text >> full_path_to_txt_file
'>' char creates file and writes firs line
'>>' char append text
check that %path%\%fol%\%NAME%.%SUFFIX% returns the Full Path to the "Xpresslisp.scr" file !
if it does, inspect the Full Path and see if it contains any white spaces.
if it does, enclose the %path%\%fol%\%NAME%.%SUFFIX% with apostrophes
"%path%\%fol%\%NAME%.%SUFFIX%"
It may be something as simple as blindly removing the last character of the installpath without knowing for sure what it is, (doublequote or backslash?).
As there is unlikely to be multiple copies of any filename in the Xpresslisp Tools tree, I would suggest something like this:
#Echo Off
Set "KEY_NAME=HKCU\Software\Laxman Enterprises\Xpresslisp Tools"
Set "VALUE_NAME=installpath"
Set "FN=loadload"
Set "FE=scr"
(Echo=FILEDIA 0
Echo=(LOAD "C:\\loadmyfile.lsp"^)
Echo=FILEDIA 1)>%FN%.%FE%
For /F "Tokens=2*" %%A In ('Reg Query "%KEY_NAME%" /v "%VALUE_NAME%"') Do (
For /F "Delims=" %%C In ('Dir/B/S/A-D "%%~B"\"%FN%.%FE%" 2^>Nul') Do (
Start "" "%ProgramFiles(x86)%\AutoCAD 2002\acad.exe" /b "%%~C"))
This doesn't care if there is a trailing backslash or not and will only run the AutoCAD command if the file is there.

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.

In a batch file, how do I get a file name from a file path?

I have a batch file that requires the user to enter a file path. Later on in the file I want to isolate just the filename and extention from the path, ie anything after the last '\'.
set FILEPATH=\\srv-01\My Docs\Templates\My SpreadSheet.xls
...
set FILENAME=???
What do i need to set FILENAME to in order for it to equal 'My SpreadSheet.xls'?
Hopefully this is fairly simple to do. Thanks!
#echo off
set FILEPATH=\\srv-01\My Docs\Templates\My SpreadSheet.xls
for /F "delims=" %%A in ("%FILEPATH%") do set "FILEPATH=%%~nxA"
echo.%FILEPATH%

For loop in batch file reading a file of File Paths

I want to write a Windows batch file script that will loop through a text file of FILE PATHS, do some work using data from each file path, then ultimately delete the file.
I started by running the FORFILES command and sending its output (the #PATH parameter is the full path of any file it matches) to a text file (results.txt).
I end up with a results.txt file like this:
"C:/Windows/Dir1/fileA.log"
"C:/Windows/Dir1/fileA.log"
"C:/Windows/Dir2/fileC.log"
"C:/Windows/Dir3/fileB.log"
What I want to do is:
Use a FOR loop and read each line in the results.txt file
For each line (file path), strip out the directory name that the log file is sitting in (ie: Dir1, Dir2, etc..) and create a directory with that SAME name in a different location (ie. D:/Archive/Backups/Dir1, D:/Archive/Backups/Dir2, etc..) -- assuming the directory doesn't exist.
Move the actual .log file to a zip file in that directory [I have code to do this].
Delete the .log file from its original location. [Pretty straightforward]
I'm having trouble figuring out the best way to accomplish the first 2 steps. My FOR loop seems to stop after reading the very first line:
FOR /F "tokens=1,2,3,4,5,6,7,8,9,10 delims=\" %%G in ("results.txt") DO (
...
)
You don't want to parse the path with the tokens/delims options because you don't know how many directory levels you are dealing with. You want to preserve each line in its entirety. TO parse the path you want to use the FOR variable modifiers. (type HELP FOR from the command line and look at the last section of the output)
%%~pG gives the path (without the drive or file name). If we then strip off the last \, we can go through another FOR iteration and get the name (and possible extension) of the file's directory by using %%~nxA.
The toggling of delayed expansion is just to protect against a possible ! in the path. If you know that no path contains ! then you can simply enable delayed expansion at the top of the script and be done with it.
EDIT - this code has been modified significantly since Aacini pointed out that I misread the requirements. It should satisfy the requirements now.
for /f "usebackq delims=" %%G in ("results.txt") do (
set "myPath=%~pG"
setlocal enableDelayedExpansion
for /f "eol=: delims=" %%A in ("!myPath:~0,-1!") do (
endlocal
if not exist d:\Archive\Backups\%%~nxA md d:\Archive\Backups\%%~nxA
rem ::zip %%G into zip file in the D: location
rem ::you should be able to create the zip with the move option
rem ::so you don't have to del the file
)
)
I wrote this to timestamp files before offloading to SFTP.
Hope you find it useful.
The timestamp coding may seem irrelevant to your issue, but I left it because it's a good example of dissecting the filename itself.
I suggest you put an ECHO in front of the REN command for testing. Different shells may have different results.
In the end, the delayedexpansion command wasn't necessary. It was the sub-routine that fixed my issues with variables inside the loop. That could possibly be because of my OS ver. (Win 8.1) - It wouldn't hurt to leave it.
#echo off
cls
setlocal enabledelayedexpansion
if %time:~0,2% geq 10 set TIMESTAMP=%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if %time:~0,2% leq 9 set TIMESTAMP=%date:~10,4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
echo TimeStamp=%TIMESTAMP%
echo.
for %%G in (*.txt) do (
set OLDNAME=%%G
call :MXYZPTLK
)
dir *.txt
goto :EOF
:MXYZPTLK
echo OldName=%OLDNAME%
ren %OLDNAME% %OLDNAME:~0,-4%_%TIMESTAMP%%OLDNAME:~-4,4%
echo.
:END
You have two minor problems:
The path separator in the file is '/' but you use '\' in the for loop.
The quotes around "results.txt" stop it working.
This works. Don't write quotes to results.txt and you won't get a quote at the end of the filename.
#echo off
FOR /F "tokens=3,4 delims=/" %%I in (results.txt) DO (
REM Directory
echo %%I
REM File
echo %%J
)

Resources