Adding users to AD with powershell

2019-08-23 11:20发布

问题:

I have a question about how to add users to AD using powershell, ive written a small script but i always get an error when i try to create a user.

$connection= "LDAP://ou=Users, dc="domain", dc="com" 
    $OU = [adsi] $Connection
            $User = $OU.Create("user", "Test Person")
            $User.Put("Firstname", "Test")
            $User.Put("Surname", Person)
            $User.Put("Email", "email@e.com")
            $User.SetInfo()

I think my connection string is wrong, but i tried different ways already and still no success. This im trying locally. Need to get it working but then normally my AD is on different server, how to do it then?

Thanks in advance.

回答1:

Give this a try:

$container = [ADSI] "LDAP://dc.sopragroup.lan/cn=Users,dc=sopragroup,dc=lan"
$UserName = "user"
$User = $container.Create("User", "cn=" + $UserName)
$User.Put("sAMAccountName", $UserName)
$User.Put("givenName", "Test")
$User.Put("sn", "Person")
$User.Put("mail", "email@e.com")
$User.SetInfo()
$User.psbase.InvokeSet('AccountDisabled', $false)
$User.SetInfo()
$User.SetPassword("P@55w0rd")


回答2:

Here is another example (@Andy Arismendi was first) with some other details:

  1. If you want to give a user and a password (log onto the server with a different user than the current one), you can use the DirectoryEntry constructor
  2. An error that is commonly done is that when you create an object in a directory, the name that represent this object in the directory tree is built with the construction : attribute=value. In Active-Directory you can't choose the the attribute it's imposed by the schema. For a user or an inetOrgPerson it's CN for an organizationalUnit it's OU. In your case the name of the object is CN=Test Person.

You'll find here under the creation of an OU and a user.

Clear-Host
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://192.168.234.200:389/dc=dom,dc=fr","administrateur@dom.fr","admin")

# Create an OU
$Monou = $dn.create("OrganizationalUnit", "ou=Monou")
#$Monou.Description = "Une description"
$Monou.put("Description", "Une description")
$Res = $Monou.Setinfo()


# Create a user
$objUtilisateur = $Monou.create("inetOrgPerson", "cn=Marc Assin")
$objUtilisateur.setinfo()

$objUtilisateur.samaccountname = "Massin"
$objUtilisateur.givenName = "Marc"
$objUtilisateur.sn = "Assin"
#$objUtilisateur.displayName = $objUtilisateur.givenName + " " + $objUtilisateur.sn
$objUtilisateur.userPrincipalName = "Massin@dom.fr"

# Pu the state of the account#$objUtilisateur.SetPassword("test.2010")
$objUtilisateur.pwdLastSet = 0
$objUtilisateur.userAccountControl = 544 

# Write the datas of the user
$objUtilisateur.SetInfo()