首页 > 解决方案 > 当以 SYSTEM 用户(批处理)运行脚本时,更改当前登录的 Windows 用户的注册表值

问题描述

我在批处理脚本中有这段代码。

REG ADD HKEY_CURRENT_USER\MyKey /ve /t REG_DWORD /d 1 /f

问题是脚本是使用系统帐户作为 Windows 中的计划任务运行的。使用系统帐户运行任务时,它不会将该值应用于当前登录的 Windows 用户的注册表。我找不到将任务设置为使用当前登录用户的方法,因此必须将其设置为使用系统帐户。

我试图使用这个解决方案;但是它不适用于当前登录的用户,因为 NTUSER.DAT 文件正在被另一个进程使用。

我还尝试导入 .reg 文件;但是,这也不适用于当前登录的用户。

我怎样才能将设置应用到HKEY_USERS\*\MyKey?最好使用批处理?或者,如何以当前登录的 Windows 用户身份运行计划任务?

标签: batch-filescheduled-tasks

解决方案


I solved this with the following code. (of course replacing MyKey)

This will apply to only signed in users registry. As I am running this code when an application is started, before it reads the registry, this works well for my case.

SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%A in ('reg query HKEY_USERS') do (
    set hive=%%A
    if "!hive:~11,8!"=="S-1-5-21" (
        if not "!hive:~-7!"=="Classes" (
            REG ADD !hive!\MyKey /ve /t REG_DWORD /d 1 /f
        )
    )
)
endlocal

If you want to apply to all users whether signed in or not then this should accomplish that.

SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%A in ('reg query HKEY_USERS') do (
    set hive=%%A
    if not "!hive:~-7!"=="Classes" (
        REG ADD !hive!\MyKey /ve /t REG_DWORD /d 1 /f
    )
)
endlocal

推荐阅读