windowsショートカットファイル パス一括置き換え コピペpython

Python

サーバーの移転等でデスクトップにある大量のショートカットファイルのリンク切れでイライラすることはありませんか?以下のpythonプログラムに置き換えたい文字列を記述すればショートファイルに登録されたパスを置き換えてくれます。
使用方法は表示されたウィンドウにショートカットをドラッグドロップするだけです。

サンプルコードでは192.168.0.1を192.168.100.1にしています。複数指定したい場合は配列のインデックスを合わせて追加してください。

なお使用の際にはバックアップをとり、自己責任で使用お願いします。

インストールモジュール

pip install pywin32
pip install tkinterdnd2 

プログラムコード

import os
import tkinter as tk
from tkinterdnd2 import DND_FILES, TkinterDnD
import pythoncom
from win32com.shell import shell, shellcon
import re


find_paths = ["192.168.0.1"] #おきかえ対象の文字列
replace_paths = ["192.168.100.1"] #おきかえ後の文字列

def replace_path_in_shortcut(original_file):
    link = pythoncom.CoCreateInstance(
        shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
    )
    link.QueryInterface(pythoncom.IID_IPersistFile).Load(original_file)
    original_path = link.GetPath(shell.SLGP_UNCPRIORITY)[0]

    for i, find_path in enumerate(find_paths):
        if find_path in original_path:
            new_path = original_path.replace(find_path, replace_paths[i])
            link.SetPath(new_path)
            link.QueryInterface(pythoncom.IID_IPersistFile).Save(original_file, True)
            break
        elif i == len(find_path)-1:
            print("置き換え対象はありませんでした。")


def drop(event):
    filepath = event.data
    filepaths_str = event.data
    filepaths = re.findall(r'\{(.*?)\}', filepaths_str)
    for filepath in filepaths:
        if filepath.endswith(".lnk"):
            replace_path_in_shortcut(filepath)
        else:
            print("This file is not .lnk file.")


def main():
    global output_folder

    root = TkinterDnD.Tk()
    root.withdraw()
    root.geometry("500x500")
    root.title('Drag and Drop')

    label = tk.Label(root, text='ここにショートカットファイルをドラッグアンドドロップしてください')
    label.pack(fill=tk.BOTH, expand=tk.YES)
    label.drop_target_register(DND_FILES)
    label.dnd_bind('<<Drop>>', drop)
    root.deiconify()
    root.mainloop()


if __name__ == "__main__":
    main()

コメント

タイトルとURLをコピーしました