Windows script create user

Powershell. Как создать локальных пользователей и добавить их в группы.

Довольно часто возникает необходимость создавать локальных пользователей на компьютерах и добавлять их в различные группы(в основном, конечно, в группу «Пользователи удаленного рабочего стола»).

Хорошо, если это один-два пользователя, тогда несложно это сделать и руками. Но если пользователей пара десятков, процесс превращается в нудный и малоэффективный.

В этом случае нам на помощь приходит Powershell, который значительно упрощает жизнь сисадмину.

Для добавления локальных пользователей пользователей на компьютер и добавление их в группу нам понадобится список пользователей в формате .csv(с указанием необходимых данных о пользователях) и небольшой скрипт Powershell. В данном случае скрипт создает пользователя, задает имя, полное имя и описание пользователя, а также добавляет его в нужные группы. При необходимости можно изменить(дополнить) файл и скрипт под свои задачи.

Файл csv можно создать в Excel с последующим сохранением в формате csv

либо создать текстовый файл в обычном блокноте и сохранить его с расширением .csv

Вот так выглядит файл в блокноте:

Если вы добавляете пользователей на виртуальной машине, нужно скопировать файл с учетными данными пользователей и сам скрипт в виртуальную машину. Как скопировать файл в виртуальную машину VMware можно узнать здесь.

Ну а вот и сам скрипт Powershell, с помощью которого вы сможете создать пользователей и добавить их в группы быстро и просто(не забудьте запустить Powershell с правами Администратора).

Use PowerShell to Create Local User Accounts

November 23rd, 2010

Summary: Microsoft Scripting Guy Ed Wilson shows how to use Windows PowerShell to create local user accounts.

Hey, Scripting Guy! I need to be able to create some local user accounts. We are still using Windows PowerShell 1.0 on our Windows 2008 servers, and on our Windows Vista workstations. Therefore, using Windows PowerShell 2.0 is not an option now. We are hoping to upgrade next year. However, we cannot make any changes now due to this being the end of the year. Can you help me?

Hello TS, Microsoft Scripting Guy Ed Wilson here. I remembered writing about this topic previously, and I decided to take a look at the Windows PowerShell Scripting Guide book that I wrote for Microsoft Press, and excerpt a portion of one of the chapters in that most excellent book.

Portions of today’s article are excerpted from Ed Wilson’s Windows PowerShell Scripting Guide, Microsoft Press, 2008.

There are two methods to create a local user account. You can use net user, or you can use Active Directory Service Interfaces (ADSI). Of course, you can still use the graphical tool seen in the following figure.

We will use ADSI to create local users and groups. To create local user accounts, we have to use the WinNT ADSI provider. Local user accounts do not have as many attributes as domain user accounts have, and so the process of creating them locally is not very difficult.

We begin the CreateLocalUser.ps1 script with the param statement where we define four parameters: -computer, -user, -password, and –help. This line of code is seen here.

param( $computer =” localhost “, $user , $password , $help )

The next section of code we have is the funhelp function. The funhelp function is used to print the help text. In Windows PowerShell 2.0, of course, there is the comment based help, but in Windows PowerShell 1.0 you must create the help text yourself. This is seen here.

Creates a local user on either a local or remote machine.

-computer Specifies the name of the computer upon which to run the script

-user Name of user to create

-help prints help file

Generates an error. You must supply a user name

CreateLocalUser.ps1 -computer MunichServer -user myUser

Creates a local user called myUser on a computer named MunichServer

Читайте также:  Как загрузить компьютер если windows не загружается

with a password of Passw0rd^&!

CreateLocalUser.ps1 -user myUser -password Passw0rd^&!

with a password of Passw0rd^&!

Creates a local user called myUser on local computer with

a password of Passw0rd^&!

Displays the help topic for the script

To determine whether we have to display help we check for the presence of the $help variable. If the $help variable is present, then we will display a string message that states we are obtaining help, and then we call the funhelp function. This line of code is seen here.

Now we have to make sure that both the –user and the –password parameters of the script contain values. We do not check password length, or user naming convention . However, we could do those kinds of things here. Instead, we just accept the user name and the password that are passed to the script when it is run. If these values are not present, then we use the throw statement to generate an error and to halt execution of the script. In Windows PowerShell 2.0, I would just mark the parameter as mandatory and therefore I could avoid this step. This section of code is seen here.

if(! $user -or ! $password )

$ (Throw ‘A value for $user and $password is required.

Try this: CreateLocalUser.ps1 -help ?’)

After we have determined that the user name value and the password string were supplied to the script, we use the [ADSI] type accelerator to connect to the local machine account database. We then use the create() method to create a user with the name supplied in the $user variable. We then call the setpassword() method to set the password. We then call the setinfo() method to write the changes to the database. Next we set the description property, and once again call setinfo(). This section of code is seen here.

$objOu = [ ADSI ]” WinNT ://$ computer “

$objUser = $objOU .Create(“ User “, $user )

$objUser .setpassword( $password )

$objUser .description = “ Test user “

The completed CreateLocalUser.ps1 script is seen here.

CreateLocalUser.ps1

param( $computer =” localhost “, $user , $password , $help )

Creates a local user on either a local or remote machine.

-computer Specifies the name of the computer upon which to run the script

-user Name of user to create

-help prints help file

Generates an error. You must supply a user name

CreateLocalUser.ps1 -computer MunichServer -user myUser

Creates a local user called myUser on a computer named MunichServer

with a password of Passw0rd^&!

CreateLocalUser.ps1 -user myUser -password Passw0rd^&!

with a password of Passw0rd^&!

Creates a local user called myUser on local computer with

a password of Passw0rd^&!

Displays the help topic for the script

if(! $user -or ! $password )

$ (Throw ‘A value for $user and $password is required.

Try this: CreateLocalUser.ps1 -help ?’)

$objOu = [ ADSI ]” WinNT ://$ computer “

$objUser = $objOU .Create(“ User “, $user )

$objUser .setpassword( $password )

$objUser .description = “ Test user “

TS, that is all there is to using Windows PowerShell to create a local user account. Because Windows PowerShell is forward compatible, this script will work on Windows PowerShell 1.0, or on Windows PowerShell 2.0. Local users week will continue tomorrow when I will talk about how to create local groups.

I invite you to follow me on Twitter or Facebook . If you have any questions, send email to me at scripter@microsoft.com or post them on the Official Scripting Guys Forum . See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Windows script create user

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Hello, is there any way to create users (local and domain) remotely (without remote desktop connection), using command lines or running a script (without install any application in destination computer) ?? (we supose that we have an administrator account in destination server).

Читайте также:  Как загрузить windows с компакт диска

for example, is there a similar command to «net user diego Pa$$word /add» but that we can use it from a PC with IP 192.168.1.101 (with any client SO like XP or 7), to create a user in another PC with IP 192.168.1.1 (with server SO like win2003 or 2008) ??

Is there also any way to do it for domain users ??

If we can’t do it using cmd, is there any script that we can run with the IP of destination computer, account name (with admin rights), password, and commands to create the users ??

Thank in advance for any help or just tell me any place or command that I may investigate.

Answers

To support XP clients, best to use a VBScript program. To create a local user on a remote computer, you can use a VBScript program similar to below:

Dim strUserName, strPassword, strComputer
Dim objComputer, objUser

‘ Specify user to create.
strUserName = «jsmith»

‘ Specify the password.
strPassword = «zxy321#»

‘ Specify NetBIOS name of computer.
strComputer = «RemoteComputer»

‘ Bind to local computer object.
Set objComputer = GetObject( «WinNT://» & strComputer)

‘ Create local user.
Set objUser = objComputer.Create( «user» , strUserName)
‘ Save the new account.
objUser.SetInfo
‘ Make account active.
objUser.AccountDisabled = False
‘ Assign password.
objUser.SetPassword strPassword
objUser.SetInfo

You must be a member of the local Administrators group on the remote computer. Generally, if you are a member of Domain Admins, that works, since this group is added to the local Administrators group when the computer is joined to the domain. To create a domain user, the VBScript program could be similar to:

Dim objOU, strName, strNTName, strPassword, objUser

‘ Specify common name of the new user object.
strName = «Jim Smith»

‘ Specify the «pre-Windows 2000 logon» name.
strNTName = «jsmith»

‘ Specify the password.
strPassword = «xYz543w»

‘ Bind to the parent OU where the new user object will be created.
Set objOU = GetObject( «LDAP://ou=Sales,ou=West,dc=MyDomain,dc=com» )

‘ Create the new user object.
Set objUser = objOU.Create( «user» , «cn=» & strName)

‘ Assign sAMAccountName (pre-Windows 2000 logon name).
objUser.sAMAccountName = strNTName

‘ Save the new object in AD.
objUser.SetInfo

‘ Enable the account.
objUser.AccountDisabled = False

‘ Assign the password.
objUser.SetPassword = strPassword
objUser.SetInfo

This can be run from any computer joined to the domain. You should be a member of Domain Admins. You do not specify a server (domain controller). There are many other attribute values you can assign, such as givenName (first name), sn (last name), displayName, etc. For more, ask in the Scripting Guys Forum:

Richard Mueller — MVP Directory Services

Thank you for the post.

I create a user.vbs in my desk, and execute it but doesn’t work (I think I have to solve the authentication problem first, but I don’t know how). Must have a way to include my credentials (ID: Martin, Pass: xxxxx) to automate the task.
Your user.vbs works well on my test computers. Your source and destination computer must have the same account with same password. So just add a Martin account on 130.1.1.1 and logged as Domain/Martin or 130.1.1.1/Martin.

Another way to create users remotely is to use psexec tool command like:
psexec \\140.1.1.1 cmd -u Martin -p PasswordXXX
net user test_user Pa$$word /add

If there are more inquiries on this issue, please feel free to let us know.

TechNet Community Support

I rarely need to use alternate credentials when I bind to a remote computer (since I use an account that is a member of Domain Admins), but when I do, I use code similar to below:

Option Explicit
Dim strComputer, strUser, strPassword, objDSO, objComputer
Dim objGroup, objMember

‘ ADS Authentication constants that can be used.
Const ADS_SECURE_AUTHENTICATION = &H1
Const ADS_USE_ENCRYPTION = &H2

strComputer = «WinNT://MyComputer»
strUser = «Administrator»
strPassword = «xYz321qq»

Set objDSO = GetObject( «WinNT:» )
Set objComputer = objDSO.OpenDSObject _
(strComputer, strUser, strPassword, _
ADS_SECURE_AUTHENTICATION OR ADS_USE_ENCRYPTION)

Once you have the objComputer object reference, you can add the rest of the code to create a local user. To force the user to change their password the next time they logon, the following should work for a local user:

Читайте также:  Bat для windows 2003

For a domain user, you assign 0 to the pwdLastSet attribute. For example:

Richard Mueller — MVP Directory Services

  • Edited by Richard Mueller MVP Sunday, April 29, 2012 12:02 AM Fixed code format
  • Marked as answer by Rick Tan Monday, April 30, 2012 1:12 AM

All replies

To support XP clients, best to use a VBScript program. To create a local user on a remote computer, you can use a VBScript program similar to below:

Dim strUserName, strPassword, strComputer
Dim objComputer, objUser

‘ Specify user to create.
strUserName = «jsmith»

‘ Specify the password.
strPassword = «zxy321#»

‘ Specify NetBIOS name of computer.
strComputer = «RemoteComputer»

‘ Bind to local computer object.
Set objComputer = GetObject( «WinNT://» & strComputer)

‘ Create local user.
Set objUser = objComputer.Create( «user» , strUserName)
‘ Save the new account.
objUser.SetInfo
‘ Make account active.
objUser.AccountDisabled = False
‘ Assign password.
objUser.SetPassword strPassword
objUser.SetInfo

You must be a member of the local Administrators group on the remote computer. Generally, if you are a member of Domain Admins, that works, since this group is added to the local Administrators group when the computer is joined to the domain. To create a domain user, the VBScript program could be similar to:

Dim objOU, strName, strNTName, strPassword, objUser

‘ Specify common name of the new user object.
strName = «Jim Smith»

‘ Specify the «pre-Windows 2000 logon» name.
strNTName = «jsmith»

‘ Specify the password.
strPassword = «xYz543w»

‘ Bind to the parent OU where the new user object will be created.
Set objOU = GetObject( «LDAP://ou=Sales,ou=West,dc=MyDomain,dc=com» )

‘ Create the new user object.
Set objUser = objOU.Create( «user» , «cn=» & strName)

‘ Assign sAMAccountName (pre-Windows 2000 logon name).
objUser.sAMAccountName = strNTName

‘ Save the new object in AD.
objUser.SetInfo

‘ Enable the account.
objUser.AccountDisabled = False

‘ Assign the password.
objUser.SetPassword = strPassword
objUser.SetInfo

This can be run from any computer joined to the domain. You should be a member of Domain Admins. You do not specify a server (domain controller). There are many other attribute values you can assign, such as givenName (first name), sn (last name), displayName, etc. For more, ask in the Scripting Guys Forum:

Richard Mueller — MVP Directory Services

Apart from Richard’s post, the below data also will makes you to understand in how to create users on simple way.

CSVDE is the command will help you to create users remotely in AD. Here is the link which will help you more how to use this command.

Also DS ADD is another command can be used to create user remotely.

Note: Login as domain admin/Enterprise admin

Also here is another helpful link for you.

Thank you Richard !

but I have a doubt, I tested it and it didn’t work because, I think, I don’t know where I have to place my credentials to login in the destination computer. For workgroup computers, can I have a diferent user in source computer than the destination computer (but I have admin account in destination) ?? For domain, can I run the script from a diferent domain (but I have an admin account in destination domain) ?? and Can I use the IP instead the computer name ??

IE: I’m in 130.1.1.1 loged as «DOMAIN1/diego», and I want to create a user in workgroup 140.1.1.1 (ping successful), where I have an Admin account named «Martin».

I create a user.vbs in my desk, and execute it but doesn’t work (I think I have to solve the authentication problem first, but I don’t know how). Must have a way to include my credentials (ID: Martin, Pass: xxxxx) to automate the task:

strComputer = «140.1.1.1»
strUserName = «test_user»
strPassword = «Pa$$word»
Set colAccounts = GetObject(«WinNT://» & strComputer & «»)
Set objUser = colAccounts.Create(«user», strUserName)
objUser.fullname = «test_remove»
objUser.description = «test_remove»
objUser.SetPassword strPassword
objUser.Put «PasswordExpired», 1
objUser.SetInfo

Thanks again for your time, I really appreciate your help !

Оцените статью