Platform SDK: Active Directory, ADSI, and Directory Services

Creating Users

Adding users is one of the most common system administration tasks. To add a user to a machine, call the Create method of the computer object:

Set newUser = myComputer.Create("user", "username")
newUser.SetInfo

Notice the call to SetInfo after creating the new user account. This call is necessary to lock in the newly created user, and must be done before modifying the new user's properties.

The following script sets up a new user and a few important properties on that user:

Dim myComputer
Dim newUser

Dim sUsername
Dim sFullName
Dim sDescription
Dim sPassword

' Set up property values for the new user
sUsername =    "adsitest"
sFullName =    "ADSI Test Account"
sDescription = "A user account for testing ADSI"
sPassword =    "password"

On Error Resume Next

Set myComputer = GetObject("WinNT://mymachine")
If Err Then AdsiErr()

' Create the new user account
Set newUser = myComputer.Create("user", sUsername)
newUser.SetInfo
If Err Then AdsiErr()

' Set properties in the new user account
newUser.FullName = sFullName
newUser.Description = sDescription
newUser.Password = sPassword
newUser.SetInfo
If Err Then AdsiErr()

Sub AdsiErr()
    Dim s
    Dim e
    
    If Err.Number = &H800708B0 Then
        WScript.Echo "The user " & sUserName & " already exists."
    Else
        e = Hex(Err.Number)
        WScript.Echo "Unexpected Error " & e & "(" & Err.Number & ")"
    End If
    WScript.Quit(1)

End Sub

Note the use of the AdsiErr subroutine to catch common errors, such as a user account of the same name as sUsername already existing on the computer. For more information about trapping and handling ADSI errors, see Errors and Error Trapping.