Skip to content

Instantly share code, notes, and snippets.

@Gunslap
Last active September 15, 2016 19:17
Show Gist options
  • Save Gunslap/bbbd127f2d2e624eec0d to your computer and use it in GitHub Desktop.
Save Gunslap/bbbd127f2d2e624eec0d to your computer and use it in GitHub Desktop.
Active Directory Account Creator - Takes in a .CSV list of full names (ie: "John Smith") and using company policy criteria, bulk creates user accounts.
<#
*****************************************************
* Active Directory Account Creator *
*****************************************************
#>
function GetHelp() {
$HelpText = @"
DESCRIPTION:
NAME: ADAccount-Create.ps1
Created By: Gunslap
Last Updated: October 31st/2013
This script will assist you in creating a unique user logon account
To run this script you must insure the "Create-Account" function is pointing to the proper location in AD
where you want the new users to be located, plus group settings, Password, Home Directory, etc.
ADAccount-Create.ps1 -help
Displays the help topic for the script
"@
$HelpText
}
#Function will generate a sutible user name based on provided values
Function User-Generate
{
$NameArray = [string[]]($FullName.split(' '))
#generate a 3 character random number
$num = ""
for ($i=0;$i -lt 3; $i++)
{
$num += get-random -minimum 0 -maximum 10
}
#build an account name (First Initial + Last Initial + 3 digits) (Our Company Policy)
$account = $NameArray[0].Substring(0,1).ToLower() + $NameArray[1].Substring(0,1).ToLower() + $num
#Check to see if the account already exists:
#Create and configure a AD Query Object:
$strFilter = "(&(objectCategory=User)(userPrincipalName=$account*))"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 10
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$colProplist = "userPrincipalName"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
#Query AD
$colResults = $objSearcher.FindAll()
$count = 0
#Count up the results
foreach ($objResult in $colResults)
{$count++}
#If that Account already exists, recall this funcation and try again
if ($count -gt 0)
{
User-Generate -FullName $FullName
}
#If the account does not exist, continue to create it
else
{
#pass to next function
Create-Account -UPN $account -FirstName $NameArray[0] -LastName $NameArray[1]
}
}
#Uses the provided information to create a new student account
Function Create-Account
{
param(
[string]$UPN = "testuser",
[string]$SAMName = $UPN,
[string]$FirstName = "Test",
[string]$LastName = "User"
)
#Find the appropriate group
$objGroup = selectGroup -groupName ($GroupName)
if (!($objGroup))
{
throw "Group does not exist! Stopping user creation."
}
#If the group does exist, continue creating the account:
if($objGroup)
{
$DisplayName = ($FirstName + " " + $LastName)
#Create a new User Object - with the user's name (Common Name)
$newUser = $container.Create("User", "cn=" + $DisplayName)
#Set the SAM Unique identifer name
$newUser.Put("sAMAccountName", $SAMName)
#Set the First name
$newUser.Put("givenName", $FirstName)
#Set the Last Name
$newUser.Put("SN", $LastName)
#Set the Display Name
$newUser.Put("displayName", ($DisplayName))
#Set the Logon Name
$newUser.Put("userPrincipalName",$SAMName + "@spirit.local")
#Set the Profile Path
$newUser.Put("profilePath", $ProfilePath)
#Set the home drive letter
$newUser.Put("homeDrive", "H:")
#Set the home directory
$newUser.Put("homeDirectory", "\\" + $Server + "\$Group$\" + $SAMName)
#Set the password to need a reset
#Finalize the previous changes
$newUser.SetInfo()
#Undisable the account
$newUser.psbase.InvokeSet('AccountDisabled', $false)
$newUser.Put("pwdLastSet", 0)
#Set the accound password
$newUser.SetPassword($Password)
$newUser.SetInfo()
#add the user to the appropriate user group:
$objGroup = [ADSI]("LDAP://" + $objGroup)
$objGroup.PSBase.Invoke("Add",$newUser.PSBase.Path)
Write-Output "Created Account: $DisplayName - $UPN`n"
Write-Output "$DisplayName - $UPN`n" | out-File $OutputFile -append
#Create the user's Home Directory
$Path = ("\\" + $Server + "\$Group$\" + $SAMName)
$DomainUser = $ADRoot + "\" + $SAMName
CreateFolder -Path $Path
#Without this sleep, it sometimes tries to set the permissions before the folder is finished being created
Start-Sleep -Second 3
SetAcl -Path $Path -Access $DomainUser -Permission FullControl
}
}
#Searches AD for the specified group and returns it as an object
function selectGroup
{
param(
[string] $groupName = $(throw "Param 'groupName' required in selectGroup.")
)
$gl = @()
$groupAttributes = @( "samaccountname", "cn", "distinguishedname", "description" )
# Create a new .net DirectorySearcher based on our domain
$searcher = New-Object System.DirectoryServices.DirectorySearcher( $script:domain )
# Specify the attributes to be returned
$searcher.PropertiesToLoad.AddRange( $groupAttributes )
# Set the filter property of the DirectorySearcher object
$typeClause = "(objectclass=group)"
$CNClause = "(cn=$groupName)"
# Put it all together
$searcher.filter = "(&$typeClause$CNClause)"
$searcher.PageSize = 1000
$groups = $searcher.findall()
$count = $groups.count
switch( $count )
{
0 {
Write-Host ""
""
}
1 {
$groups[0].properties.distinguishedname
}
default
{
# Multiple groups returned.
Write-Host "Group name is not unique."
Exit( 1 )
} # default
} # Switch
} # function
#Creates a folder on a network drive
function CreateFolder{
param(
[string]$Path
)
# Check if the folder already exists
if (Test-Path $Path)
{
Write-Host "Folder: $Path Already Exists" -ForeGroundColor Yellow
} else
{
Write-Host "Creating $Path" -Foregroundcolor Green
New-Item -Path $Path -type directory | Out-Null
}
}
#Sets the User Access Control for the Directory
function SetAcl{
param(
[string]$Path,
[string]$Access,
[string]$Permission
)
# Get te ACL on the Folder
$GetACL = Get-Acl $Path
# Set up AccessRule
$Allinherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$Allpropagation = [system.security.accesscontrol.PropagationFlags]"None"
$AccessRule = New-Object system.security.AccessControl.FileSystemAccessRule($Access, $Permission, $AllInherit, $Allpropagation, "Allow")
# Check if Access Already Exists
if ($GetACL.Access | Where { $_.IdentityReference -eq $Access})
{
Write-Host "Modifying Permissions For: $Access" -ForeGroundColor Yellow
$AccessModification = New-Object system.security.AccessControl.AccessControlModification
$AccessModification.value__ = 2
$Modification = $False
$GetACL.ModifyAccessRule($AccessModification, $AccessRule, [ref]$Modification) | Out-Null
} else
{
Write-Host "Adding Permission: $Permission For: $Access"
$GetACL.AddAccessRule($AccessRule)
}
Set-Acl -aclobject $GetACL -Path $Path
Write-Host "Permission: $Permission Set For: $Access" -ForegroundColor Green
}
#--------------------------------------------------------------------------------------------
#Variables to edit:
$FullName = Read-Host("Enter User Name:")
$Password = Read-Host("Enter User Password:") #Temporary password of the new user.
$container = [ADSI] “LDAP://ou=Accounting,dc=contoso,dc=com” #AD OU to place the new user in.
$GroupName = Read-Host("Enter User's Group Name:")
$ADRoot = "Contoso.com"
$Server = "UserServer.Contoso.Com" #Server For home directory and profile
#Profile Path:
$ProfilePath = "\\" + $Server + "\Profiles$\$GroupName\"
#--------------------------------------------------------------------------------------------
#Actual script execution begins here:
User-Generate
if ($help) { GetHelp }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment