$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