Skip to content

Instantly share code, notes, and snippets.

Created December 30, 2022 03:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A small script to add users to an AD environment based off a CSV file. More detail in my website -
You cannot pipe objects to this cmdlet
Various and sundry.
bite me
In the above example the user has specified no arguments, which will
cause Kansa to run modules per the .\Modules\Modules.conf file against
a list of hosts that it is able to query from Active Directory. Errors
and all output will be written to a timestamped output directory. If
.\Modules\Modules.conf is not found, all ps1 scripts starting with Get-
under the .\Modules\ directory (recursively) will be run.
Function GenerateStrongPassword ([Parameter(Mandatory=$true)][int]$PasswordLenght)
Add-Type -AssemblyName System.Web
$PassComplexCheck = $false
do {
If ( ($newPassword -cmatch '[A-Z\p{Lu}\s]') `
-and ($newPassword -cmatch '[a-z\p{Ll}\s]') `
-and ($newPassword -match '[\d]') `
-and ($newPassword -match '[^\w]')
} While ($PassComplexCheck -eq $false)
return $newPassword
# Opening with a Try so the Finally block at the bottom will always call
# the Exit-Script function and clean up things as needed.
Try {
$Users = import-csv -Path $CSVPath
Write-Output '### SUCCESSFULLY imported CSV ###'
Write-Output '### Processcing $($Users.Length) Users ###'
$outputcsv = [System.Collections.ArrayList] @()
foreach ($User in $Users)
$Displayname = ($User.firstname + ' ' + $User.lastname)
$UserFirstname = $User.firstname
$UserLastname = $User.lastname
$OU = $User.OU
$UPN = $
$email = $
$city = $
$country = $
$company = $
$Username = $User.username #also known as SAM
$Username = $Username.Replace(" ", "")
$jobtitle = $User.jobtitle
$department = $User.department
$password = $(GenerateStrongPassword(20))
New-ADUser -Name $Displayname -DisplayName $Displayname -SamAccountName $Username -GivenName $UserFirstname -Surname $UserLastname -Department $department -Title $jobtitle -EmailAddress $email -City $city -Country $country -Company $company -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $true -Path $OU -ChangePasswordAtLogon $true –PasswordNeverExpires $false
write-output "### Successfully added $Displayname - $username ###"
foreach ($group in $user.groups.split(',')) {
write-output "### Adding $username to $group ###"
Add-ADGroupMember -Identity $group -members $username
write-output "### Added $username to $group ###"
$outputcsv | Export-Csv -Path $OutputCsvPath -NoTypeInformation
Write-Output '### All Done ###`n'
# Clean up #
# We're done. #
Catch {
("Caught: {0}" -f $_)
Finally {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment