Create Active Directory Users PowerShell Script

房东的猫 提交于 2019-12-11 19:24:54

问题


I am trying to create five Active Directory Users (Manager1, Manager2, etc) and put them in an OU called Managers. I started by creating the OU manually in Active Directory Users and Computers. Then, I tried running the script but got this error:

"Add-ADGroupMember : Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member At (the path to the .ps1 file)

Here is my script:

Import-Module ActiveDirectory
$totalusers = 5
for ($i=0; $i -lt $totalusers; $i++) 
 { 
 $userID = "{0:00}" -f ($i + 1)
 $userName = "Manager$userID"

 Write-Host "Creating AD user" ($i + 1) "of" $totalusers ":" $userName

New-ADUser `
 -Name $userName  `
 -Path  "OU=Managers,DC=dsu,DC=com" `
 -SamAccountName $userName `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -Enabled $true
 Add-ADGroupMember "Domain Users" $userName;
}

回答1:


New active directory users are automatically added into the "Domain Users" group. You can see a simple example below:

PS C:\temp> New-ADUser webejammin 

PS C:\temp> Get-ADUser webejammin -Properties memberof


DistinguishedName : CN=webejammin,CN=Users,DC=BA,DC=NET
Enabled           : False
GivenName         : 
MemberOf          : {}

Wait? I thought I said they were automatically added to the group. So why is the memberof empty? Well the users PrimaryGroup contains the answer.

PS C:\temp> (Get-ADUser webejammin -Properties primarygroup).PrimaryGroup
CN=Domain Users,CN=Users,DC=BA,DC=NET

That is why you get the error you see. The group is there at user creation



来源:https://stackoverflow.com/questions/28633633/create-active-directory-users-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!