BradV
(Seasoned Scripter)
2007-09-24 02:15 PM
Delete key from remote computer

Good Morning,

I'm trying to delete a key on a remote computer. My account has admin privelages on the remote and local computer. They key does not have any sub-keys (it does have values). I am using kixtart 4.53 and the computers are a combination of w2k SP4 and xp SP2. When I try to delete the key, I get "The handle is invalid," error code 6. Here is a portion of the code ($strWks already has the name of the remote computer):

 Code:
$strProfReg = "\\" + $strWks + "\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
$arrProfs = ArrayEnumKey($strProfReg)
For Each $strProf In $arrProfs
   If Len($strProf) > 8
      $strSID = Right($strProf,Len($strProf)-InStrRev($strProf,"-"))
      If $strSID <> "500"
         $strPath = ExpandEnvironmentVars(ReadValue($strProfReg + "\" + $strProf,"ProfileImagePath"))
         DelDir($strPath)
         $intRetCode = DelKey($strProfReg + "\" + $strProf)
         ? @SERROR
         If $intRetCode <> 0
            ? "There was a problem deleting the registry key:"
            ? $strProfReg + "\" + $strProf
            ? "The error code is: " + $intRetCode
         EndIf
      EndIf
   EndIf
Next


There is some more code in there so that I am not deleting all the profiles. Everything else works fine, except when I try to delete the key.

Regards,

Brad V


Glenn BarnasAdministrator
(KiX Supporter)
2007-09-24 03:34 PM
Re: Delete key from remote computer

Couple of possibly obvious questions:

Does the logic work elsewhere? What about on the local computer?

Are the security settings on the registry different? Use Regedt32 instead of RegEdit to confirm.

Remote Registry enabled on the target system?

Glenn


Benny69
(MM club member)
2007-09-24 03:44 PM
Re: Delete key from remote computer

good questions all;

as well as if you reduce your script to just:
delkey("\\SomeComputerName\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList")
does it work?


BradV
(Seasoned Scripter)
2007-09-24 04:03 PM
Re: Delete key from remote computer

Well, I've been testing on my computer, which means it is local. The permissions are the the local admin group has full control and my account is a member of the local admin group on all computers. I wouldn't think there is a problem with the strings since I've already retrieved all the information. I will have it a try and see what happens.

Regards,

Brad V


BradV
(Seasoned Scripter)
2007-09-24 04:21 PM
Re: Delete key from remote computer

Just trying to delete:

 Code:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-85914438-2897524180-28975


works. If I put "\\workstation_name\" in front of it. It does not.

Regards,

Brad V


Les
(KiX Master)
2007-09-24 06:53 PM
Re: Delete key from remote computer

Where are you getting the workstation name from? If pulling it from a file, Trim() it as there could be a trailing space.

Glenn BarnasAdministrator
(KiX Supporter)
2007-09-24 08:18 PM
Re: Delete key from remote computer

Good call, Les - been bit by spaces myself in the past.

Brad - if you're manually creating the local name, I'd still look at local/group policy that could disable remote registry. Not sure if it's an all or nothing, or can be configured to block writes only.

Glenn


NTDOCAdministrator
(KiX Master)
2007-09-24 09:27 PM
Re: Delete key from remote computer

I think a policy only prevents "local" registry editing tools from running (and only default built-in tools) if you use a non Microsoft tool I think it will still run, or if you run it remotely as an Admin I think it will work.

Need to verify the ERROR CODES returned to determine what is really happening.


Mart
(KiX Supporter)
2007-09-24 09:32 PM
Re: Delete key from remote computer

 Quote:

....
"The handle is invalid," error code 6
....


From experience I would guess that there is something wrong with the name of the remote system. Been bitten by this in the past. What do you see if you just display the name of the system you got from somewhere? Is this a valid name or is there some crap like spaces or whatever in front or at the back of it?


Sealeopard
(KiX Master)
2007-09-25 05:20 AM
Re: Delete key from remote computer

Also, "ExpandEnvironmentVars" will not resolve against the remote computer but the local computer.

BradV
(Seasoned Scripter)
2007-09-25 01:03 PM
Re: Delete key from remote computer

OK, what I'm trying to do is write a script to delete all the roaming profiles from a remote computer. Retrieving the list of users and determining the correct ones to delete works. I'm now to the point where I am trying to do the file and registry deletions. That is where I am running into problems. Here is the script so far:

 Code:
Break On
Dim $SO
$SO = SetOption('Explicit',          'On')
$SO = SetOption('NoMacrosInStrings', 'On')
DIM $strWks, $strProfReg, $arrProfs, $strProf
DIM $strSID, $strPath, $strUser, $strFile, $intRetCode
$strWks = ""
While $strWks == ""
   ? "Please enter the name of the workstation you wish to delete profiles from: "
   Gets $strWks
Loop
$strWks  = Trim($strWks)
$strFile = "C:\Documents and Settings\" + @userid + "\Desktop\" + $strWks + "_profiles.ini"
; Enumerate the keys under:
; \\$strWks\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
; The local administrator key ends with "-500"
$strProfReg = "\\" + $strWks + "\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
$arrProfs   = ArrayEnumKey($strProfReg)
For Each $strProf In $arrProfs
   If Len($strProf) > 8
      ; Local accounts are short.  System is S-1-5-18, etc.
      ; Grab the last portion of the SID (after the last hyphen).
      $strSID = Right($strProf,Len($strProf)-InStrRev($strProf,"-"))
      If $strSid <> "500"
         $strPath = ExpandEnvironmentVars(ReadValue($strProfReg + "\" + $strProf, "ProfileImagePath"))
         $strUser = Right($strPath,Len($strPath)-InStrRev($strPath,"\"))
         If Left($strUser,4) <> "SMSC"
            ; Don't want to delete the SMS accounts.
            ; Which should leave us with the accounts we do want to delete.
            $intRetCode = WriteProfileStrin($strFile,SIDtoName($strProf),"Path",$strPath)
            ? "Deleting files for " + SIDtoName($strProf)
            ? "Deleting path " + $strPath
            DelDir($strPath)
            ; The directory is now gone, delete the registry key.
            $intRetCode = DelKey($strProfReg + "\" + $strProf)
            ? @SERROR
            If $intRetCode <> 0
               ? There was a problem deleting the regsitry key:
               ? $strProfReg + "\" + $strProf
               ? "The error code is: " + $intRetCode
            EndIf
         EndIf
      EndIf
   EndIf
Next
;
Function ArrayEnumKey($strRegKey)
   Dim $intIndex, $arrOfKeys[0], $strKey
   If KeyExist($strRegKey)
      $intIndex = 0
      $strKey   = EnumKey($strRegKey,$intIndex)
      While @Error = 0
         ReDim Preserve $arrOfKeys[$intIndex]
         $arrOfKeys[$intIndex] = $strKey
         $intIndex             = $intIndex + 1
         $strKey               = EnumKey($strRegKey,$intIndex)
      Loop
      $ArrayEnumKey = $arrOfKeys
   Else
      $ArrayEnumKey = ""
   EndIf
EndFunction
;
Function DelDir($strPath)
   Dim $strFilename
   $strFilename = Dir($strPath + "\*.*")
   While $strFilename <> "" And @Error = 0
      If $strFilename <> "." And $strFilename <> ".."
         If (GetFileAttr($strPath + "\" + $strFilename) & 16)
            DelDir($strPath + "\" + $strFilename)
            SetFileAttr($strPath + "\" + $strFilename, 128)
            Rd $strPath + "\" + $strFilename
         Else
            SetFileAttr($strPath + "\" + $strFilename, 128)
            Del $strPath + "\" + $strFilename
         EndIf
      EndIf
      $strFilename = Dir()
   Loop
   ; At this point, the directory should be empty.  We just need to delete it now.
   Rd $strPath
EndFunction


I've left out a lot of comments just because I had to re-type it here. I was doing my testing on my own machine. When I tried it from my machine to my co-workers, it deleted the files from my computer and still gave the invalid handle message when trying to delete the registry entry.

It looks like DelDir doesn't work remotely nor does DelKey.

Regards,

Brad V


Glenn BarnasAdministrator
(KiX Supporter)
2007-09-25 01:36 PM
Re: Delete key from remote computer

Well, remote delete using DelDir does work for me, but -
without appropriate error return coding, you won't know what's failing.

This deleted the remote Start Menu folder contents, but not the folder itself. Note the added error handling. $DelDir will be 1, 2, or 3 depending on what step failed, and will return the error code in the Exit. $DelDir will be zero on success. Honestly, this is not how I'd code it for production use - I would return 1 on success, 0 on error, but for now you need to know which step has failed.

Glenn

 Code:
$Path = '\\thatPC\c$\Documents and Settings\user3\Start Menu'

; Call DelDir, let the return value fall to the screen, 
; followed by the error value / message
DelDir($Path)
' / ' @ERROR ' / ' @SERROR ?

Function DelDir($strPath)
   Dim $strFilename
   $strFilename = Dir($strPath + "\*.*")
   While $strFilename <> "" And @Error = 0
      If $strFilename <> "." And $strFilename <> ".."
         If (GetFileAttr($strPath + "\" + $strFilename) & 16)
            DelDir($strPath + "\" + $strFilename)
            If @ERROR $DelDir = 1 Exit @ERROR EndIf
            SetFileAttr($strPath + "\" + $strFilename, 128)
            Rd $strPath + "\" + $strFilename
            If @ERROR $DelDir = 2 Exit @ERROR EndIf
         Else
            SetFileAttr($strPath + "\" + $strFilename, 128)
            Del $strPath + "\" + $strFilename
            If @ERROR Exit @ERROR EndIf
         EndIf
      EndIf
      $strFilename = Dir()
   Loop
   ; At this point, the directory should be empty.  We just need to delete it now.
   Rd $strPath
   If @ERROR $DelDir = 3 Exit @ERROR EndIf
EndFunction


BradV
(Seasoned Scripter)
2007-09-25 03:58 PM
Re: Delete key from remote computer

Thanks Glen, I'll give that a shot. deldir is just a udf I found in the collection. It doesn't have any author information, so I could not attribute it properly. \:\) I'll see what errors I'm getting from it.

Regards,

Brad V


Witto
(MM club member)
2007-09-25 05:47 PM
Re: Delete key from remote computer

ISTR that deleting user profiles on remote computers has been discussed before.
Could this thread be of some help?
http://www.kixtart.org/forums/ubbthreads...true#Post161631


NTDOCAdministrator
(KiX Master)
2007-09-26 05:59 AM
Re: Delete key from remote computer

I'm not 100% certain but I could swear there is a UDF for this already, or at least a posted script as I did one and I forget who but someone else did one as well at the same time and we compared notes, so I know it's on the board somewhere, you just need to search and find it.



Arend_
(MM club member)
2007-09-26 08:37 AM
Re: Delete key from remote computer

Just use delprof.exe from the windows 2003 resource kit and invoke that from the loginscript and your set \:\)

ChristopheM
(Hey THIS is FUN)
2007-09-26 09:21 AM
Re: Delete key from remote computer

Just an idea to bypass problem with remote commands :
write a script that delete local profiles (script A).
write a script that treats computers (script B).

in the script B, copy the script A on the remote computer and execute it with psexec. if you execute psexec -d, psexec doesn't wait for remote process to terminate, so your local script (B) can continue next computers.

I often use this method because i have about 4000 workstation to manage and it is faster. One problem with this solution is that by default, remote script has no access to network resources. If you need this, you have to give user and password to psexec


BradV
(Seasoned Scripter)
2007-09-26 01:23 PM
Re: Delete key from remote computer

I found a major part of my problem. I need to add "\c$" after the workstation name and before the path. I was just giving deldir("\\workstation\temp") for example and that won't work since temp is not a share! Duh. I am finding some other problems in the logic. It decends down a path and deletes it, but then it gets stuck trying to go parallel. I will have to look at a little closer.

As far as delprof.exe is concerned, I don't think it can work in my case. I've never used it, so I may be wrong. However, from the syntax on Microsoft's web site, it looks like it either interactively asks you which profiles to delete or it deletes based on age. I want to be able to delete a specific profile. Ideally just one profile. If I can do that, I can string it together and do multiple ones.

I would like to be able to do single profiles to assist when we rebuild someone's profile. I would like to do all profiles other than the required ones on the system for computers such as in conference rooms. With so many people logging in, the local file system often gets filled and we have to go in and manually clean it up. I just wanted to be able to script this.

I'll let you know what I find out about fixing deldir.

Regards,

Brad V


NTDOCAdministrator
(KiX Master)
2007-09-27 06:07 AM
Re: Delete key from remote computer

Okay Brad I found the script I was talking about.

Please read this post and it should help you to achieve what you're wanting to do I think.


Removing old profiles with a script
http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=161631



Note that my code removes the folders but not the data within the registry whereas the code from Christophe Melin addresses the registry.


Arend_
(MM club member)
2007-09-27 10:00 AM
Re: Delete key from remote computer

delprof can run silently, which is how I use it in my loginscripts.
However it deletes all inactive profiles, except the system accounts.


NTDOCAdministrator
(KiX Master)
2007-09-27 01:34 PM
Re: Delete key from remote computer

Well the script above should run silently and remove based on date if wanted.
Should be a bit more flexible than the Microsoft tool.


BradV
(Seasoned Scripter)
2007-10-10 01:05 PM
Re: Delete key from remote computer

OK, I've done some more testing. First, I found a small error in the logic of the deldir UDF. It was a recursive algorithm that would never delete the top directory. I put a revised version in the UDF forum (http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=181418#Post181418).

Now back to trying to delete a remote key. I simplified things by creating a dummy key and then trying to delete it. I keep getting error 6, handle is invalid.

 Code:
Dim $strWks, $strProfReg, $intRetCode
$strWks = ""
While $strWks == ""
   ? "Please enter the name of the workstation from which you wish to delete the key?"
   Gets $strWks
Loop
$strWks = Trim($strWks)
$strProfReg = "\\" + $strWks + "\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\testme"
addkey($strProfReg)
if @ERROR = 0
   ? "The key was added.  Now try to delete it."
   $intRetCode = DelKey($strProfReg)
   If @ERROR = 0
      ? "The key was deleted."
   Else
      ? "The key was not deleted.  The error code is: " + $intRetCode
      ? "The error message is: " + @SERROR
   EndIf
Else
   ? "The key was not written."
EndIf


If I remove '"\\" + $strWks +' from $strProfReg so that it works against the local computer, it works.

Is my syntax wrong? Am I missing something?

Thanks!

Brad V


Glenn BarnasAdministrator
(KiX Supporter)
2007-10-10 01:52 PM
Re: Delete key from remote computer

Not sure if I posted this, but many of us use something like this to insure that system names are wrapped in "\\" and "\" (or not!)
 Code:
;;EXAMPLES       $Server = SNVerify($Server)
;
Function SNVerify($_System, Optional $_Reverse)

  ; Isolate system name, add leading & trailing slashes if needed
  $SNVerify = IIf(Not $_Reverse And CStr($_System) <> '', '\\' + Join(Split(CStr($_System), '\'), '', 3) + '\', Join(Split(CStr($_System), '\'), '', 3))

  Exit 0

EndFunction



Then you can do
 Code:
$strWks = SNVerify($strWks)
$strProfReg =  $strWks + "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\testme"

Which will work regardless of whether $strWks contains data or not..

The function can be simplified to just add the leading & trailing slashes to the name (if the name isn't empty), but as a multi-purpose UDF, this form made more sense. I could call it with the REVERSE flag to insure that the name had no slashes for use with WMI calls, or without for file share and remote registry access.

The point here is that this insures that the registry read has the right format all the time.

What kind of remote PC are you querying? Vista turns off the remote registry service by default, and many organizations disable this for "hardening". To confirm, open RegEdit, then File/Connect to Remote System and see if you can.

Glenn


BradV
(Seasoned Scripter)
2007-10-10 08:11 PM
Re: Delete key from remote computer

I'll take a look at that in the morning. The remote pc is either w2k sp4 or xp sp2. I can remote connect to the registry.

Regards,

Brad V


NTDOCAdministrator
(KiX Master)
2007-10-10 10:01 PM
Re: Delete key from remote computer

No your code is correct. I think this is actually a BUG

Simply using DelTree works just fine.


 Code:
Dim $strWks, $strProfReg, $intRetCode, $AK
$strWks = ""
While Not $strWks
   ? "Please enter the name of the workstation from which you wish to delete the key?"
   Gets $strWks
Loop
$strWks = Trim($strWks)
$strProfReg = "\\" + $strWks + "\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\testme"
'Profile is: ' + $strProfReg ?
$AK = AddKey($strProfReg)
'Error: ' + @ERROR + ' - ' + @SERROR ?
If @ERROR = 0
   ? "The key was added.  Now try to delete it."
   $intRetCode = DelTree($strProfReg)
   If @ERROR = 0
      ? "The key was deleted."
   Else
      ? "The key was not deleted.  The error code is: " + $intRetCode
      ? "The error message is: " + @SERROR
   EndIf
Else
   ? "The key was not written."
EndIf



BradV
(Seasoned Scripter)
2007-10-11 12:47 PM
Re: Delete key from remote computer

OK, I feel like an idiot. I have to learn to RTFM more closely! \:\)

Thanks Doc!

Brad V