0
点赞
收藏
分享

微信扫一扫

Windows快捷方式备份还原脚本

Windows快捷方式备份还原脚本

适用场景

  1. 单纯备份快捷方式
  2. 安装程序迁移至其他磁盘(程序文件父子层级关系不变的情况下)
  3. 安装程序还是在原来的磁盘的位置,重建快捷方式(重装系统后,安装程序到重装前同样的路径,恢复快捷方式)

功能介绍

  1. 备份脚本所在目录的所有'lnk'后缀名的快捷方式到shortcut_backup文件目录
  2. 恢复备份时对应的快捷方式到脚本相同路径(恢复时指定磁盘盘符)

使用说明及安装教程

windows环境

运行先前条件

  • 系统提前安装好python3(理论上win7以上版本都支持)
  • 安装python后需将python路径添加至环境变量
  • 运行Re_Shortcut.bat和Reshortcut.py时需在同个目录
  • 运行脚本时,文件都存放在快捷方式所在的同个目录下

安装运行

  1. 从Python官网下载python3并安装(安装时注意勾选Add python.exe to PATH) image.png
  2. 下载Re_Shortcut.bat和Reshortcut.py文件(下载地址:https://gitee.com/cosann/omb_pyscript.git)
  3. 直接运行Re_Shortcut.bat
  4. 根据菜单提示执行对应功能(首次执行需安装环境。选项1) image.png

使用演示

1. 将文件和快捷方式放在同一目录

image.png

2. 执行Re_Shortcut.bat

image.png

3. 选择2进行备份

image.png

4. 查看备份

image.png

备份成功 image.png

5. 恢复备份

输入磁盘序号,将设所有程序文件迁移至D盘 image.png

输入d运行(支持大小写,同样效果)

image.png

查看新快捷方式路径 image.png

修改成功

其他说明

  1. 核心功能由python实现,进行bat封装是为了简易操作
  2. python 运行方式直接运行为在终端执行python脚本 image.png
  3. 仅Reshortcut.py文件即可实现备份功能
  4. 备份后生成Rebuild_shortcut.json为原先快捷方式的数据,因此只要有该json文件,使用Reshortcut.py就可以恢复原先的快捷方式
  5. python文件里保留了调试参数重写脚本的执行路径,供测试使用

初版代码示例(后续会持续更新到git仓库)

Re_Shortcut.bat

chcp 65001 > nul
setlocal enabledelayedexpansion
@echo off

rem @Author:cosann
rem @Script_Name:Re_Shortcut.bat
rem @Version:1.0
rem @Create_Date:20230309
rem @Description:
rem Windows快捷方式备份还原脚本
rem @Update content:


title "快捷方式备份还原脚本"

:main
echo "快捷方式备份还原"
echo
echo "1. 初始化环境"
echo "2. 备份快捷方式"
echo "3. 恢复快捷方式"
echo "4. 退出脚本"

set n=
set /p var="请输入序号选择执行功能:"

if "%var%" == "1" (
    echo "the number equal to 1"
    call pip install pypiwin32
    goto main
    pause >nul
) else if "%var%" == "2" (
    call python Reshortcut.py -b
    goto main
    pause >nul
) else if "%var%" == "3" (
    set /p DISK="请输入还原快捷方式的目标磁盘分区序号(例如:C D E F...)"
    set CMD=python Reshortcut.py -m !DISK!
    echo !CMD!
    !CMD!
    goto main
    pause >nul
) else if "%var%" == "4" (
    pause
    exit
) else (
    echo "input wrong number"
    goto main
    pause >nul
)

import os
import win32com.client
import re
import json
import sys
import shutil

'''
@Author:cosann
@Script_Name:Reshortcut.py
@Version:1.0
@Create_Date:20230309
@Description:
Windows快捷方式备份还原脚本
@Update content:
'''


def backup_src_shortcut(f_path):
    # 创建备份文件夹
    backup_dir = f_path + '\\shortcut_backup'
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)

    print("backup_dir: ", backup_dir)
    for link_str in os.listdir(f_path):
        if link_str.endswith('.lnk'):
            full_shortcut = os.path.join(f_path, link_str)
            # print(full_shortcut)

            shutil.copy(full_shortcut, backup_dir)
    f_result_code = 0
    return backup_dir, f_result_code


def make_target_shortcut(f_path):
    # 重写path
    # f_path = "C:\\Users\\Cosann\\Desktop\\dirs"

    # 调用函数备份快捷方式
    back_dir, result_code = backup_src_shortcut(f_path)

    print("源快捷方式备份成功,备份路径: {}\n".format(back_dir)) if result_code == 0 else print("源快捷方式备份失败")
    # if result_code == 0:
    #     print("源快捷方式备份成功,备份路径: {}".format(back_dir))

    shell = win32com.client.Dispatch("WScript.Shell")

    shortcut_list = []
    for fn in os.listdir(f_path):

        if fn.endswith('.lnk'):
            com_path = f_path + '\\' + fn
            shortcut = shell.CreateShortCut(com_path)
            shortcut_dict = {fn: shortcut.Targetpath}
            # print(fn)
            shortcut_list.append(shortcut_dict)
            # print(shortcut.Targetpath)
    print(shortcut_list)

    # 将快捷方式名称和对应的真实路径写入json文件
    with open('Rebuild_shortcut.json', 'w', encoding='utf-8') as obj:
        # obj.write(str(re_shortcut_list))
        json.dump(shortcut_list, obj)
    # print(os.stat('Rebuild_shortcut.json'))
    if os.path.exists('Rebuild_shortcut.json') and os.stat('Rebuild_shortcut.json').st_size > 2:
        print(f"\n生成数据源文件Rebuild_shortcut.json成功\n")
    else:
        print(f"\n生成数据源文件失败,请检查!\n")


def del_src_shortcut(f_src_shortcut):
    # 删除源快捷方式
    # 遍历当前文件下的所有文件
    for src_shortcut in os.listdir(os.getcwd()):
        # 若是快捷方式执行
        if src_shortcut.endswith('.lnk'):
            # 若包含在字典中
            if src_shortcut in f_src_shortcut:
                # 删除
                os.remove(src_shortcut)


def create_shortcut(f_target_disk):
    f_target_disk = target_disk + ':'

    # os.chdir('E:\\test')
    shell = win32com.client.Dispatch("WScript.Shell")

    with open('Rebuild_shortcut.json', 'r', encoding='utf-8') as obj:
        shortcut_list = json.load(obj)

    # 修改真实路径盘符
    re_shortcut_list = []
    for shortcut_dict in shortcut_list:

        #调用删除函数
        del_src_shortcut(shortcut_dict)

        # print(shortcut_dict)
        for key, value in shortcut_dict.items():  # items方法返回一个键值对列表

            re_shortcut_dict = {key: re.sub('^[A-Z]:', f_target_disk, value)}
            # print(re_shortcut_dict)
            re_shortcut_list.append(re_shortcut_dict)

    print(re_shortcut_list)

    for shortcut_dict in re_shortcut_list:
        # print(shortcut_dict)
        for key, value in shortcut_dict.items():
            # print("key=", key)
            dest_shortcut = shell.CreateShortCut(key)
            dest_shortcut.TargetPath = value
            dest_shortcut.save()
            # print("key=", key)
            print("\n快捷方式[{}]创建成功!\n".format(key))


if __name__ == '__main__':

    # target_disk = 'K'
    if sys.argv[1:]:
        array_sum = len(sys.argv[1:])

        # 位置参数2为Backup
        if sys.argv[1] == "-b" and array_sum == 1:
            # print("backup")
            scripts_path = os.getcwd()
            print("scripts_path: " + scripts_path)
            # 创建目标字典
            make_target_shortcut(scripts_path)

        # 位置参数2为Make
        elif sys.argv[1] == "-m" and array_sum == 2:
            # print("make")
            target_disk = sys.argv[2]
            # 创建快捷方式
            create_shortcut(target_disk)

        else:
            script_name = sys.argv[0]
            print("脚本用法:\n1. 备份源快捷方式数据 命令:[ {} -b ]".format(
                script_name))
            print("2. 重新创建快捷方式 命令:[ {} -m 盘符 ]".format(script_name))
    else:
        script_name = sys.argv[0]
        print("脚本用法:\n1. 备份源快捷方式数据 命令:[ {} -b ]".format(
            script_name))
        print("2. 重新创建快捷方式 命令:[ {} -m 盘符 ]".format(script_name))

有需修改的地方,欢迎提出交流~

举报

相关推荐

0 条评论