You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重启前获取Windows重命名后的区分大小写计算机名(Python实现)

获取Windows重命名后重启前的带大小写计算机名

注册表读取方案

你提到的HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName : ComputerName其实是保留输入时大小写的——你看到全大写大概率是注册表编辑器的显示问题(部分编辑器会自动将字符串值转为大写展示,但实际存储的是原始输入的大小写)。用Python的winreg模块直接读取就能拿到原始格式:

import winreg

def get_pending_computer_name():
    try:
        reg_path = r"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName"
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path, 0, winreg.KEY_READ) as reg_key:
            pending_name, _ = winreg.QueryValueEx(reg_key, "ComputerName")
            return pending_name
    except Exception as e:
        print(f"读取失败: {str(e)}")
        return None

# 使用示例
if new_name := get_pending_computer_name():
    print(f"待生效的新计算机名: {new_name}")

Python专属API方案

如果注册表读取还是不符合预期,直接调用Windows原生API是更可靠的方式。借助pywin32模块调用GetComputerNameEx,指定ComputerNamePhysicalDnsHostname类型,就能准确获取重启前的新名称(完全保留输入大小写):

先安装依赖:

pip install pywin32

实现代码:

import win32api
import win32con

def get_pending_computer_name():
    # 缓冲区大小设为Windows允许的最大计算机名长度(256字符)
    buf_size = 256
    return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname, buf_size)

# 使用示例
print(f"待生效的新计算机名: {get_pending_computer_name()}")

这个API会直接返回系统已设置但尚未生效的计算机名,无需担心注册表显示或存储的异常情况。

内容的提问来源于stack exchange,提问作者Scott Paterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:10:24