Windows: establish file association to batch file

有些话、适合烂在心里 提交于 2019-12-07 06:18:10

问题


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" %*

回答1:


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" %*



回答2:


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>



回答3:


if you are using this from a bat file try to change it to:

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

I think even

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

should work.



来源:https://stackoverflow.com/questions/28189137/windows-establish-file-association-to-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!