Skip to content

Instantly share code, notes, and snippets.

@thomasbilk
Created March 7, 2012 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasbilk/1993312 to your computer and use it in GitHub Desktop.
Save thomasbilk/1993312 to your computer and use it in GitHub Desktop.
PowerShell Script for Generating Active Directory User Accounts
firstname lastname email username
Bill Gates gates@microsoft.com bill.gates
Steve Ballmer ballmer@microsoft.com steve.ballmer
# PowerShell Script for Generating User Accounts
Import-Module ActiveDirectory
Function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
Function Check-User
{
param($NameUser)
try
{
$check = get-ADUser -Identity $NameUser
if($check)
{
$exist = 1
}
else
{
$exist = 0
}
}
catch
{
$exist = 0
}
return $exist
}
$infile = Join-Path (Get-ScriptDirectory) users.csv
$outfile = Join-Path (Get-ScriptDirectory) new_users.txt
$passwordchars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ2346789"
$passwordlenght = 8
$maxlogonNameLength = 20
$domain = "domain.name"
$newline = "`n"
$csvfile = Import-Csv -Path $infile -Delimiter ","
$csvfile | ForEach-Object {
$logonName = $_.username
if ($logonName.Length -gt $maxlogonNameLength) {
$logonName = $_.username.substring(0, $maxlogonNameLength)
}
$principalname = "{0}@{1}" -f $_.username,$domain
$displayName = "{0} {1}" -f $_.firstname,$_.lastname
$rand = New-Object System.Random($_.username.getHashCode())
$password = ""
1..$passwordlenght | ForEach {
$password = $password + $passwordchars[$rand.next(0, $passwordchars.Length - 1)]
}
$secpassword = ConvertTo-SecureString -asplaintext -force $password
if (Check-User $logonName) {
"Login name {0} already exists.$newline" -f $logonName
}
else {
try {
New-ADUser -Name $displayName -SamAccountName $logonName -DisplayName $displayName -GivenName $_.firstname -Surname $_.lastname -AccountPassword $secpassword -EmailAddress $_.email -CannotChangePassword $true -PasswordNeverExpires $true -UserPrincipalName $principalname -Enabled $true
"Login name: {0}$newline`Password: {1}$newline" -f $logonName,$password
}
catch {
"Login name {0} could not be created: $newline`{1}$newline" -f $logonName,$_.Exception.ToString()
}
}
} | Out-File $outfile
Write-Host Done
Login name: bill.gates
Password: ntE37HddTJ
Login name: steve.ballmer
Password: duT6wnGEbj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment