Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 602
  • Last Modified:

VBscript to delete a users account and move their home folder

I have a vbscript that works perfectly well at disabling an account and removing all group membership apart from the Primary Group.

What I would now like to do is delete these accounts and move the attached home folder to a new location

0
WNottsC
Asked:
WNottsC
1 Solution
 
raju1706Commented:
Hi,

Please try below code
'On Error Resume Next

struser = staffid
dest_dir_path=""   '"\\servername\drive$\deleteduser" Mention full path

Dim objRootDSE, strDomain, strUsername, objConnection, objCommand, objRecordSet, strDN
Const ADS_SCOPE_SUBTREE = 2

' Get domain components
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Set ADO connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

' Set ADO command
Set objCommand = CreateObject("ADODB.Command")
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = "SELECT distinguishedName FROM 'LDAP://" & strDomain & "' WHERE objectCategory='person' AND samaccountname = '" & struser & "'"

' Set recordset to hold the query result
Set objRecordSet = objCommand.Execute

If Not objRecordSet.EOF Then
    strDN = "LDAP://" & objRecordSet.Fields("distinguishedName").Value
    
    Set objUser = GetObject(strDN)
    Err.Clear
    home_dir = objUser.homeDirectory
    
    objfso.MoveFolder home_dir,dest_dir_path
    
	set objContainer = getobject(objUser.Parent)
	objContainer.Delete "user","cn=" & objUser.cn
    
    If Err.Number = 0 Then
        WScript.Echo "User Account Deleted."
    Else
        WScript.Echo Err.number
        WScript.Echo Err.Desciption
    End If
    
Else
    
    WScript.Echo "user not found"
    
End If

Open in new window

0
 
prashanthdCommented:
Have you tried the above solution, it should work..
0
 
WNottsCAuthor Commented:
This has worked fine thanks
0

Featured Post

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now