批量修改文件打开方式的脚本

wen 实用脚本 3

本文目录导读:

批量修改文件打开方式的脚本

  1. Windows 系统 (PowerShell)
  2. macOS 系统
  3. Linux 系统
  4. 跨平台 Python 脚本
  5. 使用建议
  6. 注意事项

Windows 系统 (PowerShell)

使用 Set-UserFTA 工具(推荐)

# 首先下载 Set-UserFTA 工具
# 下载地址:https://kolbi.cz/blog/2017/10/25/set-user-fta-user-choice-set-file-type-associations/
# 设置文件类型关联
# 格式:Set-UserFTA.exe 扩展名 程序ID
Set-UserFTA.exe .txt txtfile
Set-UserFTA.exe .pdf AcroExch.Document.DC
Set-UserFTA.exe .jpg jpegfile
# 批量修改多个扩展名
$associations = @{
    ".txt" = "txtfile"
    ".pdf" = "AcroExch.Document.DC"
    ".jpg" = "jpegfile"
    ".png" = "pngfile"
}
foreach ($ext in $associations.Keys) {
    Set-UserFTA.exe $ext $associations[$ext]
}

使用注册表方式

# 批量修改文件打开方式(注册表方法)
$fileTypes = @(
    @{Extension=".txt"; App="C:\Program Files\Notepad++\notepad++.exe"},
    @{Extension=".pdf"; App="C:\Program Files\Adobe\Acrobat Reader\Acrobat\Acrobat.exe"},
    @{Extension=".jpg"; App="C:\Program Files\IrfanView\i_view32.exe"}
)
foreach ($file in $fileTypes) {
    # 创建文件扩展名关联
    $ext = $file.Extension
    $app = $file.App
    # 设置打开方式
    cmd /c "assoc $ext="
    cmd /c "ftype $ext=`"$app`" `"%1`""
    cmd /c "assoc $ext=$ext"
}

macOS 系统

使用 duti 工具(推荐)

#!/bin/bash
# 首先安装 duti
# brew install duti
# 批量设置文件打开方式
# 格式:duti -s 应用程序包ID 扩展名 all
# 设置所有 .txt 文件用 TextEdit 打开
duti -s com.apple.TextEdit .txt all
# 设置 .pdf 文件用 Adobe Reader 打开
duti -s com.adobe.Reader .pdf all
# 批量设置多个扩展名
declare -A apps
apps[".txt"]="com.apple.TextEdit"
apps[".pdf"]="com.adobe.Reader"
apps[".jpg"]="com.apple.Preview"
apps[".png"]="com.apple.Preview"
for ext in "${!apps[@]}"; do
    app="${apps[$ext]}"
    duti -s "$app" "$ext" all
done

使用 macOS 默认命令

#!/bin/bash
# 使用 SwiftDefaultApps 工具
# 下载地址:https://github.com/Lord-Kamina/SwiftDefaultApps
# 或使用 launchctl 和 LSHandler 设置
# 修改 LaunchServices 数据库
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user

Linux 系统

使用 xdg-mime 命令

#!/bin/bash
# 批量设置默认应用程序
# 设置 .txt 文件用 gedit 打开
xdg-mime default gedit.desktop text/plain
# 设置 .pdf 文件用 evince 打开
xdg-mime default evince.desktop application/pdf
# 批量设置
declare -A mime_types
mime_types=(
    [".txt"]="text/plain"
    [".pdf"]="application/pdf"
    [".jpg"]="image/jpeg"
    [".png"]="image/png"
    [".html"]="text/html"
)
declare -A default_apps
default_apps=(
    [".txt"]="gedit.desktop"
    [".pdf"]="evince.desktop"
    [".jpg"]="eog.desktop"
    [".png"]="eog.desktop"
    [".html"]="firefox.desktop"
)
for ext in "${!mime_types[@]}"; do
    mime="${mime_types[$ext]}"
    app="${default_apps[$ext]}"
    xdg-mime default "$app" "$mime"
done

使用 desktop-file-install

#!/bin/bash
# 创建自定义的 .desktop 文件
cat > /usr/local/share/applications/my-editor.desktop << EOF
[Desktop Entry]
Name=My Editor
Exec=gedit %F
Type=Application
MimeType=text/plain;
EOF
# 更新 MIME 数据库
update-desktop-database
# 设置默认关联
xdg-mime default my-editor.desktop text/plain

跨平台 Python 脚本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import platform
import subprocess
import sys
def set_file_association_windows(extension, app_path):
    """Windows 系统设置文件关联"""
    try:
        # 使用 ftype 和 assoc
        file_type = extension[1:] + "file"  # e.g., .txt -> txtfile
        subprocess.run(f"ftype {file_type}={app_path} %1", shell=True, check=True)
        subprocess.run(f"assoc {extension}={file_type}", shell=True, check=True)
        print(f"设置 {extension} 关联成功")
    except subprocess.CalledProcessError as e:
        print(f"设置 {extension} 关联失败: {e}")
def set_file_association_macos(extension, bundle_id):
    """macOS 系统设置文件关联"""
    try:
        # 使用 duti
        subprocess.run(["duti", "-s", bundle_id, extension, "all"], check=True)
        print(f"设置 {extension} 关联成功")
    except subprocess.CalledProcessError as e:
        print(f"设置 {extension} 关联失败: {e}")
def set_file_association_linux(extension, mime_type, desktop_file):
    """Linux 系统设置文件关联"""
    try:
        subprocess.run(["xdg-mime", "default", desktop_file, mime_type], check=True)
        print(f"设置 {extension} 关联成功")
    except subprocess.CalledProcessError as e:
        print(f"设置 {extension} 关联失败: {e}")
def batch_set_associations(associations):
    """批量设置文件关联"""
    system = platform.system()
    print(f"检测到系统: {system}")
    if system == "Windows":
        for ext, app in associations.items():
            set_file_association_windows(ext, app)
    elif system == "Darwin":
        if not os.path.exists("/usr/local/bin/duti"):
            print("请先安装 duti: brew install duti")
            return
        for ext, bundle_id in associations.items():
            set_file_association_macos(ext, bundle_id)
    elif system == "Linux":
        for ext, (mime_type, desktop_file) in associations.items():
            set_file_association_linux(ext, mime_type, desktop_file)
    else:
        print(f"不支持的系统: {system}")
if __name__ == "__main__":
    # 示例配置
    # Windows 示例
    windows_associations = {
        ".txt": "C:\\Program Files\\Notepad++\\notepad++.exe",
        ".pdf": "C:\\Program Files\\Adobe\\Acrobat Reader DC\\Reader\\AcroRd32.exe",
        ".jpg": "C:\\Program Files\\IrfanView\\i_view32.exe"
    }
    # macOS 示例(需要 bundle ID)
    macos_associations = {
        ".txt": "com.apple.TextEdit",
        ".pdf": "com.adobe.Reader",
        ".jpg": "com.apple.Preview"
    }
    # Linux 示例
    linux_associations = {
        ".txt": ("text/plain", "gedit.desktop"),
        ".pdf": ("application/pdf", "evince.desktop"),
        ".jpg": ("image/jpeg", "eog.desktop")
    }
    # 根据系统使用相应的配置
    system = platform.system()
    if system == "Windows":
        batch_set_associations(windows_associations)
    elif system == "Darwin":
        batch_set_associations(macos_associations)
    elif system == "Linux":
        batch_set_associations(linux_associations)

使用建议

  1. Windows: 推荐使用 Set-UserFTA 工具,它操作简洁且不需要管理员权限
  2. macOS: duti 是最好用的工具,但需要先通过 Homebrew 安装
  3. Linux: xdg-mime 是最标准的方法,所有发行版都支持

注意事项

  1. 管理员权限: Windows 和 Linux 可能需要管理员权限
  2. 系统恢复: 建议在修改前备份注册表或系统设置
  3. 测试验证: 先在少量文件上测试,确认正确后再批量操作
  4. 程序路径: 确保指定的程序路径正确且程序已安装

选择哪种方法取决于您的操作系统和具体需求。

抱歉,评论功能暂时关闭!