Showing posts with label VBscript. Show all posts
Showing posts with label VBscript. Show all posts

02 July 2010

Import users into Active Directory from csv file

At a customer I should create a bunch of users in the domain.
I could get the users in a csv-file, containing their initials and full name.
Since there were more than 200 account, I created a script to perform this operation.



' create users in AD from csv
'
' CSV file with layout sam, displayname (, password)
'----------------------------------------------------
Option Explicit
Dim sCSVFileLocation
Dim sCSVFile
Dim oConnection
Dim oRecordSet
Dim oNewUser
Dim oRootLDAP
Dim oContainer
Dim sLogon
Dim sFirstName
Dim sDisplayName
Dim sPassword
Dim nPwdLastSet
Dim nUserAccountControl ' Used to enable the account
Dim sDomain

' AD domain, used to append to login name (initials@ADdomain)
sDomain="sc.local"

' Input file, location and filename
sCSVFileLocation = "C:\tools\"
sCSVFile = sCSVFileLocation&"NewUser.csv"

' Commands used to open the CSV file and select all of the records
set oConnection = createobject("adodb.connection")
set oRecordSet = createobject("adodb.recordset")
oConnection.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & _
   sCSVFileLocation &  ";Extended Properties=""text;HDR=yes;FMT=Delimited"""
oRecordSet.open "SELECT * FROM " & sCSVFile ,oConnection

' Create a connection to the Active Directory Users container.
Set oRootLDAP = GetObject("LDAP://rootDSE")
Set oContainer = GetObject("LDAP://ou=Users,ou=Production," & _
   oRootLDAP.Get("defaultNamingContext"))

on error resume next   ' continue if account exist

do until oRecordSet.EOF
' --------- Start creating user account
' Read variable information from the CSV file
' and build everything needed to create the account
sLogon = oRecordSet.Fields.Item(0).value
sDisplayName = trim(oRecordSet.Fields.Item(1).value)
'sPassword = oRecordSet.Fields.Item(2).value 'if specified in csv file
sPassword = "Welcome1" 'same password for all
sFirstName = split(sDisplayName," ",3,1)
  'wscript.echo sLogon & " " & sDisplayName
  'wscript.echo sFirstName(0)
  'wscript.echo sFirstName(1)
' Build the User account
Set oNewUser = oContainer.Create("User","cn="&sDisplayName)
oNewUser.put "sAMAccountName",lcase(sLogon)
oNewUser.put "givenName",sFirstName(0)
oNewUser.put "sn",sFirstName(1)
oNewUser.put "UserPrincipalName",lcase(SLogon)&"@"&sDomain
oNewUser.put "CN",sDisplayName
oNewUser.put "DisplayName",sDisplayName
oNewUser.put "Initials",sLogon     'max 6 chars
oNewUser.put "name",lcase(sLogon)

' Write to AD
oNewUser.SetInfo
' password
oNewUser.SetPassword sPassword
oNewUser.Put "pwdLastSet", 0
' Enable the user account
oNewUser.Put "userAccountControl", 512
oNewUser.SetInfo
' Used only for debugging
if err.number = -2147019886 then
   wscript.echo sLogon & " already exists"
end if
oRecordSet.MoveNext
loop

11 May 2010

Script: Change DNS settings on servers in AD

I had a customer where new DNS servers was setup (that was - new DCs with AD integrated DNS). To change DNS server settings on the Nic, facing the produktion network, on all servers in the domain, I wrote this script.

Using RootDse, no domain name is hardcoded.
The script checks the AD for servers,
then it check all NICs on the server to see if there is DNS settings matching the ip's given in strings strODNS1 and strODNS2.
If a match is found, the DNS settings are changed to the ip's given in strNDNS1 and strNDNS2.
Same is done regarding WINS settings.
A logfile - DNS.TXT - are created, listing servernames and changes made.
-------------------------------------------------------------------------------

'Change DNS and WINS on NICs

'
On Error Resume Next

'Old settings
strODNS1="192.168.1.19"
strODNS2="192.168.1.10"
strOWins1="192.168.1.19"
strOWins2="192.168.1.10"

'New settings
strNDNS1="192.168.1.19"
strNDNS2="192.168.1.100"
strNWins1="192.168.1.19"
strNWins2="192.168.1.100"

Const ADS_SCOPE_SUBTREE = 2
Const strLogFile = "DNS.TXT"
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f

'Delete log file if it exists
Set fso = CreateObject("Scripting.FileSystemObject")
if fso.FileExists(strLogFile) then
   fso.DeleteFile strLogFile
end if

WriteLog "Started: " & date
WriteLog " "

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCOmmand.ActiveConnection = objConnection
Set RootDse = GetObject( "LDAP://RootDse" )
strADSPath = "LDAP://" & RootDse.get( "DefaultNamingContext" )

objCommand.CommandText = "Select Name,operatingSystem from '" & strADSPath & "' Where objectClass='computer' and OperatingSystem='*server*'"

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
   objServer = objRecordSet.Fields("Name").Value
   wscript.echo "Checkin server: " & objServer
   WriteLog "Checking server: " & objServer
   'objOS = objRecordset.Fields("OperatingSystem").value
   'wscript.echo objOS

   strComputer = objServer
   Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
   Set colAdapters = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

   For Each objAdapter in colAdapters
      If Not IsNull(objAdapter.IPAddress) Then
         For i = 0 To UBound(objAdapter.IPAddress)
            'WScript.Echo " IP address: " & objAdapter.IPAddress(i)
            'WriteLog " IP: " & objAdapter.IPAddress(i)
         Next
      End If

      If Not IsNull(objAdapter.DNSServerSearchOrder) Then
         For i = 0 To UBound(objAdapter.DNSServerSearchOrder)
            'WScript.Echo " DNS " & objAdapter.DNSServerSearchOrder(i)
            'WriteLog " DNS " & objAdapter.DNSServerSearchOrder(i)
            if (objAdapter.DNSServerSearchOrder(i) = strODNS1) or (objAdapter.DNSServerSearchOrder(i) = strODNS2) then
               writeLog " - dns settings changed ..."
               objAdapter.SetDNSServerSearchOrder Array (strNDNS1,strNDNS2)
            end if
         Next
      End If

      'WriteLog " WINS1: " & objAdapter.WINSPrimaryServer
      'WriteLog " WINS2: " & objAdapter.WINSSecondaryServer
      if (objAdapter.WINSPrimaryServer = strOWins1) or (objAdapter.WINSPrimaryServer = strOWins2) then
         objAdapter.SetWINSServer strNWins1,strNWins2
         WriteLog " - WINS settings are changed..."
      end if
   Next

   WriteLog " "
   objRecordSet.MoveNext
Loop

Function WriteLog(aStr)
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile(strLogFile, ForAppending, True)
   f.WriteLine aStr
   f.Close
   Set f = Nothing
   Set fso = Nothing
End Function

29 April 2010

Script: List all users in AD in a csv file

This script will list all users in AD in a csv file
Showing this:
SAM navn, Full name, Description, Office, OU placering
in file users.csv, createt in same folder as the script.

I'm using RootDSE, so no need for "hardcoding" domain name.

Scriptet:

' LIST_USERS.VBS
' ver. 1.0 - 070509
'
on error resume next
Set objRootDSE = GetObject("LDAP://RootDSE")
objDomain = objRootDSE.Get("defaultNamingContext")
set objConn = CreateObject("ADODB.Connection")
set objCmd = CreateObject("ADODB.Command")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
Set objCmd.ActiveConnection = objConn
objCmd.Properties("Cache Results") = False
strFilter = "(&(objectclass=user)(objectcategory=person))"
strQuery = ";" & strFilter & ";distinguishedName;subtree"
objCmd.CommandText = strQuery
Set objFSO=Createobject("Scripting.FileSystemObject")
objCSVfile = "Users.csv"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

if objFSO.FileExists(sUsersLeft) then
objFSO.deletefile(sUsersLeft)
end if

Set objLogFile = objFSO.CreateTextFile(objCSVfile)
objLogFile.Write("SAM Name, Display Name, Description, Office, OU" & chr(13) & chr(10))
Set objRecordSet = objCmd.Execute

Do Until objRecordSet.EOF
strDN = objRecordSet.Fields("distinguishedName")
Set objUser = GetObject("LDAP://" & strDN)
strsAMAccountName = objUser.sAMAccountName
strsdisplayName = objUser.displayName
strDescription = objUser.description
strOffice = objUser.physicalDeliveryOfficeName
strOU = objUser.distinguishedName
arrOU = split(strOU,",")
strOU = ""
for each i in arrOU
if left(i,2) = "OU" then
arrTmp = split(i,"=")
strOU=arrTmp(1) & "\" & strOU
end if
next
objLogFile.Write(strsAMAccountName & ", " & strsdisplayName & ", " & strDescription & "," & strOffice & "," & strOU & chr(13) & chr(10))
objRecordSet.MoveNext
Loop
objLogFile.close
objConn.Close
Set objGroup = Nothing
Set objRootDSE = Nothing
Set objCmd = Nothing
Set objConn = Nothing