# Compare elements in arrays

**URL:** <https://forums.powershell.org/t/compare-elements-in-arrays/17448>\
**Category:** PowerShell Help\
**Created:** [August 31, 2021, 8:41pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448 "2021-08-31T20:41:30Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![GShwartz](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/gshwartz/32/1665_2.png) [@GShwartz](https://forums.powershell.org/u/GShwartz)\
**Post date:** [August 31, 2021, 8:41pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/1 "2021-08-31T20:41:31Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [August 31, 2021, 9:05pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/2 "2021-08-31T21:05:19Z")

</div>

Gil,  
Welcome to the forum. 👋🏽

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:

```auto
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.

---

<div class="post-metadata">

**Author:** ![GShwartz](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/gshwartz/32/1665_2.png) [@GShwartz](https://forums.powershell.org/u/GShwartz)\
**Post date:** [August 31, 2021, 9:47pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/3 "2021-08-31T21:47:52Z")

</div>

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](https://github.com/GShwartz/PowerShell/blob/main/AddUsers/users-advanced.csv)

Error message:

> **[ps-error](https://ibb.co/T26th3D)**
>
> Image ps-error hosted in ImgBB

```auto
#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 = @()
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [September 1, 2021, 8:13am UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/4 "2021-09-01T08:13:20Z")

</div>

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.

> **[about Requires - PowerShell](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-7.2&viewFallbackFrom=powershell-7.1)**
>
> Prevents a script from running without the required elements.

---

<div class="post-metadata">

**Author:** ![GShwartz](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/gshwartz/32/1665_2.png) [@GShwartz](https://forums.powershell.org/u/GShwartz)\
**Post date:** [September 1, 2021, 12:18pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/5 "2021-09-01T12:18:55Z")

</div>

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 🙂

**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!

---

<div class="post-metadata">

**Author:** ![GShwartz](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/gshwartz/32/1665_2.png) [@GShwartz](https://forums.powershell.org/u/GShwartz)\
**Post date:** [September 3, 2021, 3:31pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/6 "2021-09-03T15:31:42Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [September 3, 2021, 3:57pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/7 "2021-09-03T15:57:36Z")

</div>

> [@GShwartz](#):
>
> 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.

Great. I’m glad it helped. 👍🏽

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

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:21pm UTC](https://forums.powershell.org/t/compare-elements-in-arrays/17448/8 "2024-05-16T20:21:37Z")

</div>

Closed on May 16, 2024, 8:21pm UTC


