batch-file - 临时设置文件关联

标签 batch-file

我有一个可移植开发工具,想在其他 PC 上使用。我想设置一个文件关联,以便单击一个文件打开该工具。然后,当我完成后,我想撤消或重置该 PC 上的文件关联。

有没有办法做到这一点?可能来自批处理文件?

最佳答案

那么,您可以使用 ftypeassoc 命令来创建或删除文件类型关联:

ASSOC .foo=FooFile
FTYPE FooFile=X:\Foo\foo.exe %1 %*

您可以稍后删除它们

FTYPE FooFile=
ASSOC .foo=

编辑:我现在尝试使用一些东西让您可以将关联重置为默认值。我把它放在my Subversion repo .在当前阶段,它会生成两个新的批处理文件:set.cmdreset.cmd;其中一个设置了一个新的关联,另一个将其反转。将 set.cmd 滚动到实际的批处理中应该不会太困难,但它会让这里的测试变得很糟糕,所以我将把它留作练习。

下面是代码,应该有足够的注释,希望如此。

@echo off
setlocal enableextensions enabledelayedexpansion
rem Debug flag. Generates a little more output; un-set if undesired
set DEBUG=1

rem Parse arguments and help
if [%1]==[] goto Usage
if [%2]==[] goto Usage

rem Find out whether the association is taken
for /f "usebackq tokens=2* delims==" %%x in (`assoc .%1 2^>nul`) do set assoc_old=%%x
if defined DEBUG (
    if defined assoc_old (echo Association already defined: [%assoc_old%]) else (echo Association not yet taken)
)

rem Find a new, unused association
rem Note that we assume that we find one, eventually. This isn't guaranteed, but we'll ignore that for the moment
rem Otherwise this loop might run forever
:loop
    set assoc_new=My.%1.%RANDOM%
    if defined DEBUG echo Trying new association (%assoc_new%)
    assoc .%1 >nul 2>nul
    if errorlevel 1 (
        set assoc_new=
        if defined DEBUG echo Didn't work out
    ) else (
        if defined DEBUG echo Found one! \o/
    )
if not defined assoc_new goto loop

if defined DEBUG echo Writing reset batch file
echo @echo off>reset.cmd
echo assoc .%1=%assoc_old%>>reset.cmd
echo ftype %assoc_new%=>>reset.cmd

if defined DEBUG echo Writing setting batch file
echo @echo off>set.cmd
echo assoc .%1=%assoc_new%>>set.cmd
echo ftype %assoc_new%=%2 %%1>>set.cmd

goto :eof

:Usage
echo.Usage
echo.  %~nx0 type command
echo.
echo.  type      is the file type to override, such as docx or txt.
echo.            No dot before it is necessary.
echo.  command   is the command to perform on that file.
echo.            %%1 is automatically appended at the end.
echo.            If the command includes spaces, surround it with quotes.
echo.
echo.Example
echo.  %~nx0 txt notepad

exit /b 1

关于batch-file - 临时设置文件关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113434/

相关文章:

windows - 要求用户输入(/P)时批处理脚本中的语法错误

windows - 奇怪的批处理文件问题

batch-file - 从批处理文件中按顺序运行多个 ant 构建

postgresql - 如何通过批处理文件中的 pg_dump 备份所有数据库 - postgres

java - Xslt Saxon 处理器 - 目录中的所有文件

windows - 将字符串作为参数发送到批处理脚本中时,^ 会加倍

batch-file - 用空格替换文件夹名称中的点的批处理脚本

variables - BAT 文件 : variable contents as part of another variable

batch-file - 使用 robocopy 时如何跳过现有和/或相同大小的文件

batch-file - DOS 批处理 FOR 循环与 FIND.exe 正在删除空白行?