change registry value for currently logged in Windows user, when running script as SYSTEM user (batch)

匆匆过客 提交于 2020-04-17 20:24:28

问题


I have this code in a batch script.

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

The problem is the script is run using the system account as a scheduled task in Windows. When using the system account to run the task it does not apply the value to the currently logged in Windows user's registry. I could not find a way to set the task to use the currently logged in user, so had to set it to use the system account.

I attempted to use this solution; however it does not apply to the currently logged in user because the NTUSER.DAT file is being used by another process.

I also attempted to import a .reg file; however that also does not apply it to the currently logged in user.

How can I make apply the setting to HKEY_USERS\*\MyKey? Preferably using batch? Alternatively how can I run a scheduled task as the currently logged in Windows user?


回答1:


This first resolve SID via WMI than fill SID into the reg command. Try it..

for /f "delims=" %a in ('wmic useraccount where "name='%username%'" get sid') do for /f "delims=" %b in ("%a") do REG ADD HKEY_CURRENT_USER\%b /ve /t REG_DWORD /d 1 /f



回答2:


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


来源:https://stackoverflow.com/questions/60661104/change-registry-value-for-currently-logged-in-windows-user-when-running-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!