Compare elements in arrays

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.
What i’m basicly trying to do is to add a disabled account to a future ou for future handling when time comes.

$oulist_csv contains the current AD ou’s and groups
$ADsimilarOU contains the ou’s that are already in AD and similar to the OU in the file.
$CSVgrp_list contains the groups in the users file.

here’s the code:

foreach ($item in $oulist_csv) {
$gname = $item.Name
$fou = $item.DistinguishedName
}

foreach ($f in $ADsimilarOU) {
if ("$fou" -like “’$($CSVgrp_list[0])_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 $f -AccountPassword (convertto-securestring
“Ab123456!” -AsPlainText -Force) -ChangePasswordAtLogon $True
Write-Host “user $username created in OU: $fou” -ForegroundColor Green

                }
            }

Thank You!

Gil,
Welcome to the forum. :wave:t4:

It’s hard to read and to understand your code when you do not format as code. To do this you place the cursor on an empty line and click the preformatted text button ( </> ). Then you paste your code. It will look like this:

foreach ($item in $oulist_csv) {
    $gname = $item.Name
    $fou = $item.DistinguishedName
}

foreach ($f in $ADsimilarOU) {
    if ($fou -like "'$($CSVgrp_list[0])_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 $f -AccountPassword (convertto-securestring "Ab123456!" -AsPlainText -Force) -ChangePasswordAtLogon $True
        Write-Host "user $username created in OU: $fou" -ForegroundColor Green
    }
}

Your two loops are completely unrelated to each other. I actually did not understand what you’re trying to do but you either need a nested loop or you should save the information you use as input in one CSV file where you already have them related to each other.

Thanks for replying!

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.
Users file

Error message:

#Verify User Privilleges.
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---------------------------------------------------------
#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 = @()

    foreach ($base in $users) {
        $usern = $base.Username
        $SearchB = $base.OU

        $ADsimilarOU = Get-ADOrganizationalUnit -LDAPFilter '(name=*_Future)' -SearchBase $($SearchB) -SearchScope 2 | Select-Object DistinguishedName
    }
    
    $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 ";") {
                    Add-ADGroupMember $g -Members $username
                    $TempGList += $g
                    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 ("$fou" -like "'$($CSVgrp_list[0])_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 $f -AccountPassword (convertto-securestring "Ab123456!" -AsPlainText -Force) -ChangePasswordAtLogon $True
                        Write-Host "user $username created in OU: $fou" -ForegroundColor Green
                            
                    }
                }

                $TempGList = @()    
                foreach ($g in $group -split ";") {
                    Add-ADGroupMember $g -Members $username
                    $TempGList += $g
                    
                    Write-Host "$username Added to $g" -ForegroundColor Green
                }

                $TempGList = @()
            }

            $ADsimilarOU = @()
        }
    }
}

Wow … that’s a big chunk of code. I will not have time today to look over it. But most of the time it helps to split the big task into smaller ones. You may start with a simple small task and if that small task runs without problems you extend it with the next stept and so forth.

For your first lines of code I already have some tips:

Instead of checking for admin rights and actively loading the modules you may use the #Requires statement.

Thank you very much!
that’s how I started and got stuck for a while on the group loop, now i’m really stuck on the OU but i’ll try some more ideas.

I will definitely change the admin check to Requires -RunAsAdministrator

So that already shaved few more lines off the code and that’s a huge yes yes :slight_smile:

Edit:
After trying that, it works but I would like to translate the error msg to human language since as you probably know, the majority of NetAdmins are totally lazy to read some “random text colored in red”.

Thanks again!

Follow up:
After taking your advice I took the code apart and not only did I manage to get it working, it’s now much much shorter and elegant.

Thanks again!

Great. I’m glad it helped. :+1:t4:

If you like you can share it here. It might help others having similar problems and maybe we can improve it even more. :wink:

1 Like