DOS batch argument substring in one line - batch-file

I have a batch file with the following 2 lines and change them into one line of code:
set arg=%1%
"C:\Program Files\TextPad 6\TextPad.exe" -u "D:\www\%arg:~14,-1%"
The context is that I'm using a webpage url-handler as described on
http://msdn.microsoft.com/en-us/library/aa767914%28v=vs.85%29.aspx
Currently I'm doing it by setting the batch file as the url command, so the %1 is passed into that, then converted and then it runs the text-editor. But I'd rather do it all in the url command, so that I don't have to use the batch file any more.

After much trial & error, I found this works:
cmd.exe /v:on /c set arg=%1& start /D"C:\Program Files\TextPad 6" TextPad.exe "D:\www\!arg:~14,-1!"

Related

Pass parameter in bat file to run from desktop short cut

I want to run a bat file from a desktop shortcut and pass a parameter to it.
I can run it from DOS with no problem.
When I try to run it from a desktop shortcut, I can enter the parameter, but it does not get passed.
I enter a file name like 20200103.txt and the bat file takes the .txt extension off so that only the first part of the file is used later in the bat file
Here are the first couple lines that I am using in the bat file
SET /I %1 DTE = %1
set %~n1 = %1%
ECHO %1
ECHO %1%
ECHO %~n1%
Is there any way to include a document when I submit a question?
When you are passing an argument for a file in a shortcut, you need to surround it with "" so if you want to pass 20200103.txt as arg 1 to the batch file you would put in the shortcut path\thing\thing\file "20200103.txt". Also, your code may not be working properly because /I is not an option is the "set" command. Like compo said, try checking out set /?

how to make batch file handle spaces in file names

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

Create a batch file to run a command with arguments multiple times

I use the following command to export data from a source file to target file in CSV format.
C:\MyApp.EXE -export "C:\Test\Sample.dat" "C:\Test\results.CSV"
However I need to repeat the same command multiple times just by changing the source and target files. something like this
C:\MyApp.EXE -export "C:\Test\Sample01.dat" "C:\Test\results01.CSV"
C:\MyApp.EXE -export "C:\Test\Sample02.dat" "C:\Test\results02.CSV"
C:\MyApp.EXE -export "C:\Test\Sample03.dat" "C:\Test\results03.CSV"
I'm looking to create a batch file to do the job. I have tried the following in a batch file and ran, but it is opening multiple console windows all at the same time. I want all this to happen in just one Command window and run the commands one after the other.
cd "C:\Test\"
start MyApp.EXE -export "C:\Test\Sample.dat" "C:\Test\results.CSV"
start MyApp.EXE -export "C:\Test\Sample01.dat" "C:\Test\results01.CSV"
I want code to create a batch file which runs MyApp.exe multiple times with arguments.
I'm using PowerShell to generate the batch file, so I don't need variables in the .bat file.
This task could be done with following batch file:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
for %%I in ("C:\Test\Sample*.dat") do (
set "FileNameCSV=%%~nI"
set "FileNameCSV=!FileNameCSV:Sample=results!"
C:\MyApp.exe -export "%%I" "%%~dpI!FileNameCSV!.csv"
)
endlocal
Command FOR searches in specified directory C:\Test for all files matching the wildcard pattern Sample*.dat. For each file the fully qualified file name (drive + path + name + extension) is assigned to loop variable I.
The first command in body command block of FOR loop assigns just the file name to environment variable FileNameCSV. On this line a DAT file name with one or more exclamation marks would not be interpreted as most users expect. The exclamation mark(s) would be interpreted as beginning/end of a delayed expanded environment variable reference. However, this is no problem here according to file names in question.
The second SET command line uses a simple case-insensitive string substitution to replace all occurrences of sample by results in CSV file name.
The environment variable must be referenced with delayed expansion using !VariableName! syntax. Otherwise the Windows command line interpreter cmd.exe would expand (= replace) the reference of the environment variable on using %VariableName% on parsing entire command block starting with ( and ending with matching ) before FOR is executed at all.
The third command line executes your application with the input file name with full path and extension and the CSV file name also with full path of input file, but with modified file name and a different file extension.
But faster would be following batch code also working for files with ! in fully qualified file name.
#echo off
for %%I in ("C:\Test\Sample*.dat") do C:\MyApp.exe -export "%%I" "%%~dpI_%%~nI.csv"
ren "C:\Test\_Sample*.csv" "results*.csv"
The FOR loop executes your application with each *.dat as input file and with _*.csv as output file, i.e. _Sample.csv, _Sample01.csv, ...
The CSV files are renamed after finishing processing all DAT files to results.csv, results1.csv, ...
Adding the additional underscore is necessary to rename all _Sample*.csv correct to results*.csv. The number of characters before wildcard character * must be the same in current and new file name.
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.
echo /?
endlocal /?
for /?
ren /?
set /?
setlocal /?
But I do not really understand why all this is done with a batch file executed by Windows command line interpreter cmd.exe if this batch file is really created with a PowerShell script executed by script interpreter powershell.exe. All this can be done also from within the PowerShell script by using the appropriate PowerShell script functions.

Novice Batch Issue- Creating Files

I was working on developing a batch program that would scan various sections of a PC, and log them to a file. Surprisingly, I was unable to have the program create the file to write to. I then tried to create a file, that I was fairly certain would work; it is as followed:
#echo off
ipconfig > ip.txt
timeout 5
However, this was also unable to write to the file ip.txt. I also attempted the following program, with no success.
#echo off
echo Test > test.txt
timeout 3
If anyone would be able to give advice, I would much appreciate it.
No error messages are present, and clicking the link batch file
Issue Resolved, downgraded to Win7 from Win10 and no longer experiencing the issue. Not a great fix.
ipconfig > %userprofile%\desktop\ip.txt
Use full paths. This specifies your desktop as the place to put the file.
See Set /? for help and type set to see standard variables.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's =
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed =
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files =
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution =
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 =
is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. =
Single % sign at command prompt and double % sign in a batch file.

Would somebody explain for a beginner what the line with FOR command does?

I'm new on batch script writing, and I have to change some line in batch code.
I need to understand what the command line below means:
for /f %%i in ('logicals -t file_location') do set DIR=%%i
It gets the result of command logicals -t file_location and sets the first part (parts are delimited with space) of the result to the DIR variable. Here's more info
have on mind that logicals command is not native command in windows , nut is an external utility.
That is Windows Batch for assign output of program to variable.
For more information see Reading the output of a command into a batch file variable.
You can find out all about batch commands by typing for /? in the command prompt.
One thing to consider is that the for command works slightly differently in a batch file compared to just running the command on the command line because you have to double up the %% characters.
For this question what this command is doing is running the command
'logicals -t file_location' and then each line of output from that command (which I assume is a path specifier) is then passed as an argument to the dir command.
for /f: Loop command: against a set of files - conditionally perform a command against each item.
Syntax:
FOR /F ["options"] %%parameter IN (filenameset) DO command
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
Source: http://ss64.com/nt/for_f.html

Resources