I'm working on a start script, and I have a text file output.txt, containing paths to programs, like:
C:/program1.exe
C:/abab/program2.exe
How do I now run the programs contained in the text file via a batch script?
for /f "usebackq delims=" %A in ("C:\output.txt") Do Start "" "%A"
Start starts programs without waiting for them to exit (so new window) and first set of quotes is the window title. UseBackq is needed to use quotes around output.txt. See For /? and my answer here for how to start programs Trouble with renaming folders and sub folders using Batch. In a batch use %%A and %A when typing interactively (I don't use batch files, I keep stuff in one text file and paste parts into a command prompt window,which is interactive).
If they were to be run sequentially then
Rename the file to batch and run it. Open in notepad and search for / and replace with \ as that is the windows standard (although autocorrect will fix it without telling you but can sometimes cause problems).
Related
I have the following batch file to make git diff invoke spreadsheet compare UI in windows. So I'm trying to pass the git diff's 2nd (old file) and 5th (new file) arguments to spreadsheet compare in order to make it compare the file using git diff.
So now, this batch file only successfully handles files with NO spaces in the file names, it CANNOT handle files with spaces in the file names.
What code should I add to this script to make this batch code handles file with spaces:
#ECHO OFF
set path2=%5
set path2=%path2:/=\%
ECHO %2 > tmp.txt
dir %path2% /B /S >> tmp.txt
C:/"Program Files"/"Microsoft Office"/root/vfs/ProgramFilesX86/"Microsoft Office"/Office16/DCF/SPREADSHEETCOMPARE.EXE tmp.txt
It currently throw errors like this:
Unhandled Exception: System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.IO.Path.GetFileName(String path)
at ProdianceExcelCompare.Form1.StatusReady()
at ProdianceExcelCompare.Form1.Init()
at ProdianceExcelCompare.Form1..ctor(String instructionFile)
at ProdianceExcelCompare.Program.Main(String[] args)
fatal: external diff died, stopping at London comparison.xlsx
See the following answers on Stack Overflow:
How to set environment variables with spaces?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
They explain the recommended syntax set "VariableName=variable value" to define an environment variable and the reasons recommending this syntax.
Why does ECHO command print some extra trailing space into the file?
It explains why the space character left to redirection operator > on an ECHO command line is also written into the file as trailing space and how to avoid this safely on variable text written into the file.
See also Microsoft documentation about Using command redirection operators.
On other command lines than ECHO a space left to > is usually no problem.
It is in general wrong to use multiple times " within an argument string like a file or folder path. There should be just one " at beginning and one " at end. This is explained by help of Windows command processor output on last help page on running in a command prompt window cmd /?.
The Microsoft documentation about Naming Files, Paths, and Namespaces explains that the directory separator on Windows is \ and not / and therefore / should not be used in batch files on Windows in file/folder paths.
The help output on running in a command prompt window call /? explains how the arguments of a batch file can be referenced with which modifiers.
The code rewritten according to information posted above and on the referenced pages:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
>"tmp.txt" echo %2
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
The first line in tmp.txt contains the second argument as passed to the batch file, i.e. without or with surrounding double quotes.
The following code is necessary to write the second argument safely always without " into file tmp.txt even on second argument passed to the batch file is "Hello & welcome!":
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
set "Argument2=%~2"
setlocal EnableDelayedExpansion
echo !Argument2!>"tmp.txt"
endlocal
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
>tmp.txt echo %~2 cannot be used as not working for something like "Hello & welcome!". Windows command processor would interpret the first string separated by normal space, horizontal tab, comma, equal sign, or no-break space (in OEM code pages) delimited string after & as command or application to execute as described by single line with multiple commands using Windows batch file.
"tmp.txt" could be written everywhere in both batch files also with just tmp.txt. But it is never wrong to enclose the complete file/folder argument string in double quotes even on not being really necessary because of the string does not contain a space or one of these characters &()[]{}^=;!'+,`~. So it is good practice to always enclose a complete file/folder argument string in double quotes. For example running a replace on both batch files searching for tmp.txt and using as replace string %TEMP%\%~n0.tmp would result in using instead of tmp.txt in current directory a temporary file with name of batch file as file name and file extension .tmp in directory for temporary files independent on what is the name of the batch file and what is the path of the directory for temporary files.
The last suggestion is reading this answer for details about the commands SETLOCAL and ENDLOCAL.
The temporary file should be also deleted finally before reaching an exit point for batch file execution.
You can use quotes as below:
It treats the string in quotes as a title of the new command window. So, you may do the following:
start "" "yourpath"
Found it in the below link :
https://ccm.net/forum/affich-16973-open-a-file-with-spaces-from-batch-file
I have a ton of files containing em dashes within the file name.
I am having trouble renaming them, as cmd apparently fails to recognize it, and converts emdash into a regular dash.
As a result I get the following error after I run the ren command:
ren "MyFile With – EmDash.txt" "MyFile.txt"
The system cannot find the file specified.
Things I have tried
Inserting chcp 65001 at start of batch code.
This command does not seem to work.
Saving the batch file as ANSI in Notepad
What this does is basically the following:
ren "MyFile With û EmDash.txt" "MyFile.txt"
The system cannot find the file specified.
As one can guess apparently saving ANSI format changes a character stored as em dash in notepad to û when batch file runs in a cmd window.
I have got dozens of files which need this renaming, and this would be monotonous to do so without a batch script.
I have a batch script that needs to run as admin. I will be distributing to users so it would be best if they can run it from Windows Explorer.
Unfortunately, it doesn't work when run from explorer (right click -> run as admin). It does work when called from a pre-existing admin terminal.
Initially I thought the problem was with the active directory, but I added a "cd /d %~dp0" as the first command. I confirmed through echo that this places them both in the same directory, but it still fails when running from explorer.
The failure occurs when reading an external file in the same directory as the .bat. It pulls empty strings when run from explorer. Here is sample code:
rem Make sure active directory is correct (verified that this works)
cd /d %~dp0
rem Load parameters from params.txt
for /f "delims== tokens=1,2" %%G in ("params.txt") do set %%G=%%H
rem Print params (it's a loop so you can read it when running from expl.)
for /l %%a in (1 1 100000) do echo %DST%
Then you just need to make sure params.txt is in same directory as .bat and includes the line "DST=some\directory\name"
Anybody know why this doesn't work?
As has been pointed about by #nephi12 in his answer if your file name does not have spaces you can remove the quotes, otherwise it thinks the IN clause is a string you want to parse. If you need to quote your file names then you need to use the USEBACKQ option as pointed out by the comments. Once you use that option your code works just fine.
But I would like to make a point with your code. If the contents of your params.txt file is:
"DST=some\directory\name"
Then your FOR command can just be this:
for /f "usebackq tokens=1 delims=" %%G in ("params.txt") do set %%G
I am not understanding why you are echoing the %dst% variable 100,000 times?
For one thing, take away the "s from around params.txt as double-quotes means string parsing, while unquoted is a list of files.
Second, try prepending params.txt with %~pd0\ to ensure the correct path, rather than changing directory.
So basically, let's say I have the following folders in a directory:
test_folder_1
test_folder_2
And I also have a text file with the list of all the folders in that directory.
How can I create a script that will create a text file, test.txt, in all the folders in the directory? (test_folder_1 and test_folder_2)?
I tried modifying some code I found online and got this:
for /F "tokens=1 delims=," %%v IN (folderlist.txt) DO echo test>"C:\Users\myname\My Documents\test\"%%v""
However, running this, I get "Access Denied."
Any idea what went wrong, or alternative ways to do this? Thanks.
The command
echo test>"C:\Users\myname\My Documents\test\"%%v""
despite the wrong double quotes around %%v redirects the text test directly to the directory instead of a file test.txt in the directory. Or in other words: The attempt to create a file with name of an already existing directory is denied by Windows and the result is the access denied error message.
The solution for creating a file test.txt with the line test in each directory specified in text file folderlist.txt is:
for /F "tokens=1 delims=," %%v in (folderlist.txt) do echo test>"%USERPROFILE%\My Documents\test\%%v\test.txt"
It is also possible to create a file test.txt with a file size of 0 bytes in all subfolders of the test folder with following command line in the batch file.
for /D %%v in ("%USERPROFILE%\My Documents\test\*") do echo. >nul 2>"%%v\test.txt"
The command FOR returns in this case the subfolder name with full path always without surrounding double quotes even if the folder path contains a space character as it is the case here.
See How to create empty text file from a batch file? and read the Microsoft article about Using command redirection operators for more details.
echo. >nul 2>test.txt results in writing just a new line to STDOUT redirected to device NUL to avoid printing lots of blank lines on batch execution to screen. And to the file text.txt nothing is redirected from STDERR as there is no error message printed by command ECHO resulting in creating an empty test.txt file.
Run in a command prompt window for /? for help on command FOR.
I have several bat files on network. I like to create one bat so I can run all one time. Also I like to use *.bat in new bat so I don't need copy each bat files.
Using the FOR command you can locate files with a wildcard in the name and then run all of them in sequence.
FOR /F "usebackq " %%F in (`dir "%~dp0filename*.BAT`) DO Call "%~dp0%%~F"
This code will list all files that start with "filename" and end in ".bat" and then rin them. This use of the FOR command will work in folders with spaces in the name. It will even run from a UNC path (one that start with \ and is located on a network share).