添加文件夹到我的电脑
Talk is cheap. Let me show you my code.
- 如下图,将某个文件夹添加到"我的电脑"中,便于快速跳转

- 下面是python脚本,有详细注释和使用帮助
import winreg
import uuid
import argparse
import sys
import winreg
import subprocess
# 注册表路径
NAMESPACE_PATH = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace"
CLSID_PATH = r"SOFTWARE\Classes\CLSID"
def add_folder(name, path, icon_index):
"""添加自定义文件夹到 '此电脑',并设置指定图标"""
guid = str(uuid.uuid4()).upper() # 生成唯一 GUID
try:
# 在 "This PC" 中创建命名空间
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{NAMESPACE_PATH}\\{{{guid}}}") as key:
pass
# 在 CLSID 下创建 GUID 信息
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}") as key:
winreg.SetValueEx(key, None, 0, winreg.REG_SZ, name)
winreg.SetValueEx(key, "System.IsPinnedToNameSpaceTree", 0, winreg.REG_DWORD, 1)
winreg.SetValueEx(key, "DescriptionID", 0, winreg.REG_DWORD, 3)
# 绑定 InProcServer32 以确保 Windows Explorer 正确识别
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}\\InProcServer32") as key:
winreg.SetValueEx(key, None, 0, winreg.REG_SZ, r"%SystemRoot%\System32\shell32.dll")
winreg.SetValueEx(key, "ThreadingModel", 0, winreg.REG_SZ, "Both")
# 绑定到 Explorer 的 Folder 类型
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}\\Instance") as key:
winreg.SetValueEx(key, "CLSID", 0, winreg.REG_SZ, "{0E5AAE11-A475-4c5b-AB00-C66DE400274E}")
# 让 Windows 识别该文件夹的目标路径
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}\\Instance\\InitPropertyBag") as key:
winreg.SetValueEx(key, "TargetFolderPath", 0, winreg.REG_SZ, path)
winreg.SetValueEx(key, "Attributes", 0, winreg.REG_DWORD, 0x11) # 确保它是一个有效的文件夹
# 确保 Windows 识别它为 **文件夹**,而不是驱动器
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}\\ShellFolder") as key:
winreg.SetValueEx(key, "Attributes", 0, winreg.REG_DWORD, 0xf080004d) # 重要: 确保它是文件夹
winreg.SetValueEx(key, "FolderValueFlags", 0, winreg.REG_DWORD, 0x29) # 让 Windows Explorer 识别为文件夹
# 添加用户自定义的文件夹图标
icon_path = f"%SystemRoot%\\System32\\imageres.dll,-{icon_index}"
with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, f"{CLSID_PATH}\\{{{guid}}}\\DefaultIcon") as key:
winreg.SetValueEx(key, None, 0, winreg.REG_SZ, icon_path)
print(f"✅ Successfully added '{name}' (Path: {path}) to 'This PC'.")
print(f"📌 GUID: {guid}")
print(f"🎨 Icon set to: {icon_path}")
except PermissionError:
print("❌ Error: This script requires administrator privileges.")
print("🔹 Try running the script as an administrator.")
except Exception as e:
print(f"❌ An unexpected error occurred: {e}")
def list_folders():
"""列出 '此电脑' 里的自定义文件夹"""
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, NAMESPACE_PATH) as key:
index = 0
folders = []
while True:
try:
subkey_name = winreg.EnumKey(key, index) # 获取 GUID
guid = subkey_name.strip("{}")
# 获取文件夹名称
try:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, f"CLSID\\{{{guid}}}") as clsid_key:
name, _ = winreg.QueryValueEx(clsid_key, None)
except FileNotFoundError:
name = "Unknown"
folders.append((guid, name))
index += 1
except OSError:
break
if folders:
print("📂 Custom folders in 'This PC':")
for guid, name in folders:
print(f" {guid} - {name}")
else:
print("⚠️ No custom folders found in 'This PC'.")
except PermissionError:
print("❌ Error: This script requires administrator privileges.")
print("🔹 Try running the script as an administrator.")
except Exception as e:
print(f"❌ An unexpected error occurred: {e}")
def delete_registry_key(root, subkey):
"""递归删除注册表项及其所有子项"""
try:
with winreg.OpenKey(root, subkey, 0, winreg.KEY_ALL_ACCESS) as key:
while True:
try:
subkey_name = winreg.EnumKey(key, 0) # 获取第一个子项
delete_registry_key(root, f"{subkey}\\{subkey_name}") # 递归删除
except OSError:
break
winreg.DeleteKey(root, subkey)
print(f"🗑️ Successfully deleted: {subkey}")
except FileNotFoundError:
print(f"⚠️ Not found: {subkey}")
except PermissionError:
print(f"❌ Permission Denied: {subkey}. Run script as administrator.")
def remove_folder(guid):
"""删除 '此电脑' 里的自定义文件夹"""
try:
guid = guid.strip("{}")
# 1️⃣ 删除 `NameSpace` 下的 GUID
namespace_key = f"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MyComputer\\NameSpace\\{{{guid}}}"
delete_registry_key(winreg.HKEY_LOCAL_MACHINE, namespace_key)
# 2️⃣ 删除 `CLSID` - **必须递归删除所有子项**
clsid_key_path = f"SOFTWARE\\Classes\\CLSID\\{{{guid}}}"
delete_registry_key(winreg.HKEY_LOCAL_MACHINE, clsid_key_path)
print(f"✅ Successfully removed folder with GUID: {guid}")
except PermissionError:
print("❌ Error: This script requires administrator privileges.")
print("🔹 Try running the script as an administrator.")
except Exception as e:
print(f"❌ An unexpected error occurred: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Manage custom folders in 'This PC' on Windows.",
epilog="Examples:\n"
" python thispc_folder_manager.py add 'MyFolder' 'D:\\MyFolder' 112\n"
" python thispc_folder_manager.py list\n"
" python thispc_folder_manager.py remove <GUID>\n",
formatter_class=argparse.RawTextHelpFormatter
)
subparsers = parser.add_subparsers(dest="command")
# 添加文件夹
add_parser = subparsers.add_parser("add", help="Add a custom folder to 'This PC'")
add_parser.add_argument("name", type=str, help="Custom folder display name")
add_parser.add_argument("path", type=str, help="Custom folder target path")
add_parser.add_argument("icon_index", type=int, nargs="?", default=112, help="Icon index (Default: 112 for Documents)")
# **修正:添加 list 命令**
list_parser = subparsers.add_parser("list", help="List all custom folders in 'This PC'")
# **修正:添加 remove 命令**
remove_parser = subparsers.add_parser("remove", help="Remove a custom folder by its GUID")
remove_parser.add_argument("guid", type=str, help="GUID of the folder to remove")
args = parser.parse_args()
if args.command == "add":
add_folder(args.name, args.path, args.icon_index)
elif args.command == "list":
list_folders()
elif args.command == "remove":
remove_folder(args.guid)
else:
parser.print_help()