Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows: establish file association to batch file

I created a custom file extension I would associate to a batch script. I used

ASSOC .myext=MY.FILETYPE
FTYPE MY.FILETYPE=cmd /c "C:\Path\of\my\batch.bat" %1 %*

by now the batch file "C:\Path\of\my\batch.bat" is a simple one-liner

echo %1

And roughly works: double clicking a .myext file pops up a cmd shell echoing the file path.
But a problem arises when the .myext file is in a path containing spaces: the echoed filepath is truncated to the space.
Double quoting the %1 in the FTYPE statement seems not to work.

FTYPE MY.FILETYPE=cmd /c "C:\Path\of\my\batch.bat" "%1" %*
like image 687
Federico Destefanis Avatar asked Jan 28 '15 09:01

Federico Destefanis


2 Answers

Change the batch file "C:\Path\of\my\batch.bat" content to

echo %*

Your ASSOC and FTYPE statements seem to be all right.

Edit accordig to Monacraft's comment.

This solution is correct as %1 will reference the document filename while that %* will reference to further parameters: If any further parameters are required by the application they can be passed as %2, %3. To pass all parameters to an application use %*.

Handy for using aFile.myext a b c right from command line, although for that use the FTYPE statement should be

FTYPE MY.FILETYPE=cmd /D /C "C:\Path\of\my\batch.bat "%1"" %*

to differentiate first parameter if contains spaces.

Example: with

ASSOC .xxx=XXXFILE
rem a bug here FTYPE XXXFILE=%ComSpec% /D /C "d:\bat\xxxbatch.bat "%1"" %*
rem definitely switched to Jeb's solution as follows
FTYPE XXXFILE=%comspec% /D /C call "d:\bat\xxxbatch.bat" "%1" %*

and xxxbatch.bat as follows

@echo(
@echo %*
@if "%2"=="" pause
@goto :eof

Output:

d:\bat>D:\test\xxxFileNoSpaces.xxx aa bb cc

"D:\test\xxxFileNoSpaces.xxx"  aa bb cc

d:\bat>"D:\test\xxx file with spaces.xxx" dd ee

"D:\test\xxx file with spaces.xxx"  dd ee

d:\bat>
like image 37
JosefZ Avatar answered Sep 29 '22 15:09

JosefZ


Double quoting %1 is correct, but it fails as cmd.exe contains a bug when the command and at least one parameter contains quotes.
So you need to make the command without quotes by inserting CALL.

FTYPE MY.FILETYPE=cmd /c call "C:\Path\of\my\batch.bat" "%1" %*
like image 124
jeb Avatar answered Sep 29 '22 14:09

jeb