I’ve just started learning PowerShell and as a method to learn i took on a project to create a script that automatically add
Users to AD from a csv file.
I’ve managed to get to the point where the users are added to the correct groups but I keep creating them in different OU’s.
I must be missing something in the IF condition and I would appreciate some guidance.
Basicly, this is designed to save some time for the network admin.
lets say the admin got an e-mail from HR with a spreadsheet file containing new arrivals and the admin needs to create their AD accounts.
New arrivals are disabled with default password with reset at login and added to the specific department’s “_Future” OU
Maybe it would be more helpful if I place the full script and a link to the users file.
My focus is on the disabled account, once I manage to fix it i'll be able to adjust the code for the enabled accounts.
Example user file:
https://github.com/GShwartz/PowerShell/blob/main/AddUsers/users-advanced.csv
Lab structure:
https://ibb.co/wCLFWzL
Error message:
https://ibb.co/T26th3D
Code:
If (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You are not running this as local administrator. Run it again in an elevated prompt."
Break
}
#Import AD Module & Type.
Import-Module ActiveDirectory
Add-Type -AssemblyName System.Windows.Forms
#Load a .CSV file.
$file = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
}
#Open the file window.
$null = $file.ShowDialog()
#Place imported file in variable.
$filepath = $file.FileName
$users = Import-csv $filepath
#----------------------------------------BLOCK---------------------------------------------------------
#Get Active Directory OU and Group lists and save to csv file.
$OUListPath = "c:\users\gilush\desktop\OUList.csv"
$OUList = Get-ADOrganizationalUnit -Properties DistinguishedName -Filter * | Sort-Object DistinguishedName |
ForEach-Object {
[pscustomobject]@{
Name = $_.Name
DistinguishedName = $_.DistinguishedName
}
}
$OUList | Export-Csv C:\Users\gilush\Desktop\OUList.csv -NoTypeInformation -Encoding UTF8
$oulist_csv = Import-Csv $OUListPath
#----------------------------------------BLOCK---------------------------------------------------------
#Show Help in header.
Write-Host "==============================================================================="
Write-Host ""
Write-Host "You can also add to groups outside of the parent OU for example:"
Write-Host "The group Managers is in OU=Users so type Managers as parent"
Write-Host ""
Write-Host "==============================================================================="
Write-Host ""
#----------------------------------------BLOCK---------------------------------------------------------
#Get additional groups names from the user.
$parent_groups = @()
do {
$parent = Read-Host "Enter parent group (blank for none)"
#Check if the group exists.
try {
$group_exists = Get-ADGroup -Identity $parent
$parent_groups += $parent
Write-Host "Groups Selected: $parent_groups"
}
catch {
if ($parent -eq "") {break}
Write-Warning "Group $parent does not exists."
}
}
#If user hits ENTER on an empty string the loop will stop.
until ($parent -eq "")
#----------------------------------------BLOCK---------------------------------------------------------
#Get input for user account status.
$ustat = $null
do {
$user_status = Read-Host "Should the users be [E]nabled or [D]isabled?"
}
until ($user_status -like "e" -or $user_status -like "d")
if ($user_status -like "e") {
$ustat = $True
} else {$ustat = $false}
#----------------------------------------BLOCK---------------------------------------------------------
foreach ($base in $users) {
$SearchB = $base.OU
$ADsimilarOU = Get-ADOrganizationalUnit -LDAPFilter '(name=*_Future)' -SearchBase $($SearchB) -SearchScope 2 | Select-Object DistinguishedName
}
#Check if the additional groups list is empty.
if ($parent_groups.Length -eq 0) {
Write-Host ""
Write-Warning "**************************************************************************************"
Write-Warning " No Parent Group Selected. "
Write-Warning "**************************************************************************************"
Write-Host ""
$ADsimilarOU = @()
$CSVgrp_list = @()
foreach ($u in $users) {
$group = $u.Group
foreach ($g in $group -split ";") {
if ($g -in $CSVgrp_list){continue}
else {$CSVgrp_list += $g}
}
}
if ($ustat){
foreach ($User in $users){
$firstname = $User.Firstname
$lastname = $User.Lastname
$username = $User.SamAccountName
$password = $User.Password
$group = $User.Group
$OU = $User.ou
#Check if the user is already in Active Directory.
if (Get-ADUser -F { SamAccountName -eq $username }) {
Write-Warning "A user account with username $username already exists in Active Directory."
$TempGList = @()
foreach ($g in $group -split ";") {
Add-ADGroupMember $g -Members $username
$TempGList += $g
}
$TempGList = @()
}
else {
Write-Host "Creating user: $username..." -ForegroundColor White
New-ADUser -SamAccountName $username -UserPrincipalName "$username@gilush.local" -Name "$firstname $lastname" -GivenName $firstname -Surname $lastname -Enabled $ustat -DisplayName "$lastname, $firstname" -Path $OU -AccountPassword (convertto-securestring "Ab123456!" -AsPlainText -Force) -ChangePasswordAtLogon $True
$TempGList = @()
foreach ($g in $group -split ";") {
$TempGList += $g
Add-ADGroupMember $g -Members $username
Write-Host "$username Added to $g" -ForegroundColor Green
Write-Host ("User $username created in group: CSV: $TempGList | OU: $OU | Enabled: $ustat") -ForegroundColor Green
}
$TempGList = @()
}
}
}
if (-not $ustat) {
foreach ($User in $users){
$firstname = $User.Firstname
$lastname = $User.Lastname
$username = $User.SamAccountName
$password = $User.Password
$group = $User.Group
$OU = $User.ou
#Check if the user is already in Active Directory.
if (Get-ADUser -F { SamAccountName -eq $username }) {
Write-Warning "A user account with username $username already exists in Active Directory."
$TempGList = @()
foreach ($g in $group -split ";") {
Add-ADGroupMember $g -Members $username
$TempGList += $g
}
$TempGList = @()
}
else {
foreach ($item in $oulist_csv) {
$gname = $item.Name
$fou = $item.DistinguishedName
}
foreach ($i in $CSVgrp_list) {
if ($gname -like "$($i)_Future") {
$fgroup = $gname
}
}
foreach ($f in $ADsimilarOU) {
if ("$f" -like "'$($OU)'" -and "$f".Length -lt "'$($ADsimilarOU)'".Length) {
$add_ou = "$($CSVgrp_list)_Future"
Write-Host "Creating user: $username in $fou ..." -ForegroundColor White
New-ADUser -SamAccountName $username -Name "$firstname $lastname" -GivenName $firstname -Surname $lastname -Enabled $ustat -DisplayName "$lastname, $firstname" -Path $add_ou -AccountPassword (convertto-securestring "Ab123456!" -AsPlainText -Force) -ChangePasswordAtLogon $True
Write-Host "user $username created in OU: $fou" -ForegroundColor Green
}
}
$TempGList = @()
foreach ($g in $group -split ";") {
$TempGList += $g
foreach ($ag in $TempGList) {
Add-ADGroupMember $ag -Members $username
Write-Host "$username Added to $ag" -ForegroundColor Green
}
}
$TempGList = @()
}
$ADsimilarOU = @()
}
}
}