简体   繁体   中英

Renaming/Deleting keys in the registry via batch cmd

When a user in Windows 7 logs in and the profile is corrupt they get a blank profile. I can fix easily enough by going to the registry and deleting the temporary profile, setting the refcount and state values. I'm getting stuck in my batch as my extraction from the registry is adding 2 spaces to the registry key name once I call for it in the batch. If I echo %SID% it returns the correct value without visible space. The registry does have %SID% and %SID%.bak

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /F "skip=1 delims=" %%j in ('wmic useraccount where name^="%username%" get SID') do (
  set SID=%%j
  goto :DONE
)
:DONE
echo  SID=%SID%

reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%SID%.bak"
pause

The result of the batch:

 SID=S-1-5-21-1559011707-81249799-2450556423-1000
Permanently delete the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Window
s NT\CurrentVersion\ProfileList\S-1-5-21-1559011707-81249799-2450556423-1000  .b
ak (Yes/No)? y
ERROR: The system was unable to find the specified registry key or value.
Press any key to continue . . .

As you can see the output is putting 2 spaces after the SID & the file extension

Any ideas?

WMI query results are encoded in UCS-2 LE, not ANSI. When capturing the output of wmic , I find it's helpful sometimes to add a disposable column to the query and use /format:csv to retain the formatting.

@echo off
setlocal

for /f "tokens=2 delims=," %%I in (
    'wmic useraccount where "name='%username%'" get SID^,Status /format:csv'
) do set "SID=%%I"

rem // echo result
set SID

MarcB is right, the var is incorrect because space at end.
You can check white-space with quotes in echo and solve it with delims= "

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /F "skip=1 delims= " %%j in ('wmic useraccount where name^="%username%" get SID') do (
  set SID=%%j
  goto :DONE
)
:DONE
echo  SID = '%SID%'
pause
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%SID%.bak"
pause

Just add this:

  set SID=!SID: =!

this will delete all space!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM