Skip to content

Create OU, AD Group and member users

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
$VerbosePreference = 'continue'

$ClientPrefix = 'Client1'
$ClientOUBasePath = 'OU=Client Users,DC=domain,DC=local'
$ClientOUPath = "OU=$ClientPrefix,OU=Client Users,DC=domain,DC=local"
$ClientGroup = "All $ClientPrefix Users"
$UserInfo = @{}
$Users = 'user1',
'user2',
'user3'

# Check if OU exists
if (-not ([adsi]::Exists("LDAP://$ClientOUPath")))
{
  Write-Verbose -Message "Creating OU: $ClientPrefix"
  New-ADOrganizationalUnit -Name $ClientPrefix -Path $ClientOUBasePath
}
else 
{
  Write-Verbose -Message 'OU already exists'
}

# Check if AD Group exists
$GroupExists = Get-ADGroup -LDAPFilter "(SAMAccountName=$ClientGroup)"

if ($null -eq $GroupExists)
{
  Write-Verbose -Message "Creating AD Group: $ClientGroup"
  New-ADGroup -Name $ClientGroup -Path $ClientOU -GroupScope Global
}
else 
{
  Write-Verbose -Message 'AD Group already exists'
}

# Perform User operations
foreach ($User in $Users)
{
  $User = ([string] $User).Replace(' ','').ToLower()
  $Username = $ClientPrefix + '-' + $User
  $AccountPassword = [System.Web.Security.Membership]::GeneratePassword(12,1)
  $SecureAccountPassword = ConvertTo-SecureString -String $AccountPassword -AsPlainText -Force
  New-ADUser -Name $Username -ErrorAction Continue -AccountPassword $SecureAccountPassword -DisplayName $Username -Enabled $true
  $UserInfo.add($Username,$AccountPassword)
  Add-ADGroupMember -Identity $ClientGroup -Members $Username -ErrorAction SilentlyContinue
  $UsernameDN = (Get-ADUser $Username).DistinguishedName
  Get-ADUser -Identity $Username | Move-ADObject -TargetPath $ClientOUPath
}

# Display account creation info
$UserInfo | Out-GridView