Create users script errors

I am trying to make a batch script that creates users in AD, creates theri home folders, shares them and sets permissions on them etc.

I get some errors:
::-0 returns error
When i put "OU=Tilsatte," cmd runs ok but with "OU=Tilsatte,OU=Test," it does not create the user

::-1 returns error
no mapping between account names and security id was done

::-2 returns error
(this is obvious as a result of error # 0 and 1)
The user name could not be found

(userlist=Surname,Firstname,Username,Password)
The file looks like this:
::MKDIR for all users
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do MKDIR F:\Brukere\Test\%%C
 
::Share folder for user
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do net share %%C$=F:\Brukere\Test\%%C
 
::-0 returns error
::Create users in AD + Assign homedir
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do dsadd user "CN=%%B_%%A,OU=Tilsatte,OU=Test,DC=lan,DC=fofo,DC=ffnx,DC=no" -samid %%C -fn %%B -ln %%A -display "%%B_%%A" -pwd %%D -HMDRV H: -HMDIR \\phobos\Brukere\Test\%%C
 
:: Set permissions on users folders
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G Administrator:F
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G "Account Operators":C
 
::-1 returns error
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G %%C:C
 
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /R Everyone
 
::-2 returns error
:: Set logon times
FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do net user %%C /times:M-Su,07:00-23:00

Open in new window

i686Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Serge FournierAnalyst ProgrammerCommented:
windows batch script still exist?

you  should use VBS (wsh, windows script host)
you can get access to the ldap objects easier
here is a script (.VBS) that will scan all my ladp users and change some initials according to a sql database list of users
it is a good base to start accessing you ldap with vbscript
and you have some good keywords in it to search google for the follow up

this is far from a complete answer

it will detect the ldap root object automatically

i will make a user creation script later with a web interface to manage it (dynweb)
but right now i am at the  step of adding employee number in my ldap to sync  my employees with another database

'=== reference program
 
'=== will scan ldap and all sub dir in ldap to find something
 
dim x(10)
 
Set objFSO = wscript.CreateObject("Scripting.FileSystemObject")
thepath=WScript.ScriptFullName
p = instrRev(thepath,"\")
basedir  = left(thepath,p)
 
a = "zz_log_fini_TOUT" & basename & ".txt"
 
Set objFil02 = objFso.OpenTextFile(basedir & a, 2, true)
If Err.number <> 0 Then
   Set objFil02 = objfso.OpenTextFile("c:\_stas\logs\" & a, 2, true)
end if
 
Set con_02 = CreateObject("ADODB.Connection")
sql1 = "sql.corp.stas.local"
 
con_02.ConnectionString = "Driver={SQL Server};Server=" & sql1
con_02.Open
con_02.commandtimeout = 1200 'secondes
 
objFil02.WriteLine date & " " & time & " === log ldap start"
 
Set oRootDSE = GetObject("LDAP://RootDSE")
Set oDomain = GetObject("LDAP://" & oRootDSE.Get("DefaultNamingContext"))
on error goto 0
 
'msgbox("debut")
 
Call EnumOUs(oDomain.ADsPath)
 
objFil02.WriteLine date & " " & time & " END"
 
con_02.close
 
msgbox("fin")
 
'=== end all code
wscript.quit
 
'================================ sub scan ldap
 
Sub EnumOUs(sADsPath)
	Set oContainer = GetObject(sADsPath)
	oContainer.Filter = Array("OrganizationalUnit")
	For Each oOU in oContainer
		EnumUsers(oOU.ADsPath)
		EnumOUs(oOU.ADsPath)
	Next
End Sub
 
Sub EnumUsers(sADsPath)
   Set oContainer = GetObject(sADsPath)
   
   'objFil02.WriteLine date & " " & time & " " & sADsPath
   
   oContainer.Filter = Array("User")
   For Each oADobject in oContainer
      'if instr(lcase(sadspath),lcase("OU=Usagers"))<>0 then
         'if instr(lcase(sadspath),lcase("OU=comptes génériques"))=0 then
            
            '=== code traitement des usagers
            a = trim(lcase(oADobject.sn))
            b = trim(lcase(oADobject.givenname))
            
            x(0) = a +", "+ b           ' name and prename
   	        'if a = "fournier" and b = "serge" then
   	        '   msgbox(oADobject.employeeNumber)
   	        '   oADobject.put "employeeNumber", "6225"
   	        '   oADobject.SetInfo
   	        'end if
   	        'objUser.Put "employeeNumber", strEmpID
   	        x(1) = oADobject.Description
   	        'rs_01(2) = oADobject.Initials
   	        x(2) = oADobject.sAMAccountName                          ' login
   	        'on error resume next
   	        x(3) = oADobject.employeeNumber               ' account expiration date
   	        'employeeNumber
   	        on error goto 0
            if a<>"" and b<>"" and _ 
            instr(a,"services")=0 and _ 
            instr(a,"voyages")=0 and _ 
            instr(a,"scanner")=0 and _ 
            instr(a,"salle")=0 then
               'objFil02.WriteLine x(0)
               sql = "SELECT count(*) as 'dbcount' FROM [mag_employés].[dbo].[personnes] where nom='" & x(0) & "' and code<>'0'"
               Set TAG = con_02.Execute(Sql)
               a = tag("DBCount")
               if a=1 then
                  sql = "SELECT [code], [divers9] FROM [mag_employés].[dbo].[personnes] where nom='" & x(0) & "' and code<>'0'"
                  Set TAG = con_02.Execute(Sql)
                  While Not (TAG.EOF)
                     'objFil02.WriteLine x(0) & " --- " & tag("code") & " --- " & tag("divers9")
                     if tag("divers9")<>oADobject.Initials then
                        objFil02.WriteLine x(0) & " --- " & tag("code") & " --- divers9: " & tag("divers9") & " --- initialsldap: " &  oADobject.Initials
                        oADobject.Put "Initials", cstr(tag("divers9"))
                        oADobject.SetInfo
                     end if
                     'objFil02.WriteLine oADobject.employeeNumber
                     
                     oADobject.SetInfo
                     tag.movenext
                  wend
               end if
            end if
            'Set objUser = GetObject("LDAP://cn=Jim Smith,ou=Sales,dc=MyDomain,dc=com")
            'objUser.AccountExpirationDate = #04/22/2007 15:30#
            'objUser.SetInfo
 
         'end if
	  'end if
   Next
   end sub

Open in new window

0
i686Author Commented:
Thanks for the input, it's much appreciated, but i'm really just looking to get the batch file working. Batch files are still very handy ways for sysadmins, that are not scripters, to get many things done fast. Win2k8 login scripts are still batch files, you know :-) This is no login script, thoug, but .bat files still does a lot of the "dirty-work" for me. I suppose at some point i'll have to look into learning PowerShell scripting, but not today.
0
Robin CMSenior Security and Infrastructure EngineerCommented:
Depending on how the add process works, if the user already exists in a different OU to that which you specify the add will fail.

e.g. if user1 exists in OU=Tilsatte and then you try and add user1 again, this time to OU=Tilsatte,OU=Test it will fail as you can only have one object in AD with a particular name, irrespective of OU location.

An OU is obviously not the same as a folder on disk in this respect.
0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

dlb6597Commented:
is your OU structure

Tilsatte
     Test

or


Test
   Tilsatte

as written, your dsadd command assumes the latter structure.  If your structure is actually the former example, your dsadd command should contain  "...OU=Test,OU=Tilsatte..."
0
i686Author Commented:
dlb6597: Thanks, that solves the first error.
OU structure =

Tilsatte
     Test

2 more to go. I will accept multiple solutions on this question

FOR /F "delims=, tokens=1,2,3,4" %%C in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G %%C:C

::-1 returns error:
no mapping between account names and security id was done

Even though the user is created, the next part of the script can't actually find the user in AD



0
dlb6597Commented:
how many domain controllers do you have? The new ID may not have replicated to other DCs/sites...

0
i686Author Commented:
Only 1 DC. Is it possible i have to run 2 .bat files? 1 to create the users and later 1 to set permissions + modify users?
0
dlb6597Commented:
if your username is the third token in userlist.txt, the variable you want is probably %%E (or change to Tokens=3 in your CACLS line...

also you can specify multiple user names after /G and do all permissions with one CACLS command...

and I put "Echo y|" in front of my CACLS command so I don't have to answer yes to the Are you Sure? prompt....

0
i686Author Commented:
There is no variable %%E. As far as i know tokens=1,2,3,4 means 4 variables:  %%A, %%B, %%C and %%D. And in the commandline for sharing the folders, the %%C variable works for the username.

userlist=Surname,Firstname,Username,Password
userlist=%%A,%%B,%%C,%%D

I found out now that the ::Create users in AD + Assign homedir part works fine with the variables, but in the other parts, for some reason, it says %%C but infact the data from the variable %%A is used in its place, so when the command runs, it looks for the surname as the usename. To summarize: In  the ::Create users in AD + Assign homedir part %%A ia %%A and %%C is %%C but everywhere else i put %%C i get %%A's input.
0
dlb6597Commented:
did you try my suggestion?  Tokens=1,2,3,4 does mean 4 variables, BUT it starts at the variable you specify...so with "FOR /f... %%C..." your 4 variables become %%C, %%D, %%E, %%F...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
i686Author Commented:
I see. So the script should be like this:
::MKDIR for all users
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do MKDIR F:\Brukere\Test\%%C
 
::Share folder for user
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do net share %%C$=F:\Brukere\Test\%%C
 
::Create users in AD + Assign homedir
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do dsadd user "CN=%%B %%A,OU=Test,OU=Tilsatte,DC=lan,DC=follo,DC=fhs,DC=no" -samid %%C -fn %%B -ln %%A -display "%%B %%A" -pwd %%D -HMDRV H: -HMDIR \\phobos\%%C$
 
:: Set permissions on users folders
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G Administrator:F
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G "Account Operators":C
 
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /G %%C:C
 
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do CACLS F:\Brukere\Test\%%C /E /T /R Everyone
 
:: Set logon times
FOR /F "delims=, tokens=1,2,3,4" %%A in (c:\userlist.txt) do net user %%C /times:M-Su,07:00-23:00

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Project Management

From novice to tech pro — start learning today.