I'm writing a PowerShell script that needs to check if items in array $arrayEmail are in array $empListEmail and throw those values in another array C. Array A has 9,500 items and array B doesn't have many. Surprisingly, I have not seen an example that performs this. I've been searching Google for two days. Here is what I have now, but the comparison doesn't work at all like it should.
function MatchUsers {
$array = Get-Content -Raw -Path PassDataOut.json | ConvertFrom-Json
Import-Module ActiveDirectory # Load the Active Directory module
Set-Location AD: # Change into Active Directory
set-location "DC=graytv,DC=corp" # Sets the location to the Gray TV Corporate directory
$empList = Get-ADUser -filter 'Enabled -eq "False"' -searchbase "OU=domain Users,DC=graytv,DC=corp"
$arrayTemp = $array.Email
$arrayEmail = $arrayTemp.trim()
$empListEmail = $empList.UserPrincipalName
$NotInList = @($arrayEmail) -notin $empListEmail
Write-Host $NotInList
CodePudding user response:
One option you would likely get for this when googling may have been Compare-Object
, but using the -notin
operator works as well. The issue comes from attempting to compare the entirety of the list to another list. You have to iterate through the contents to check against the list:
$arrayEmail.Where{$_ -notin $empListEmail}
CodePudding user response:
Turn the second list into a HashSet<string>
- it'll be much faster to search than an array:
$empListEmail = [System.Collections.Generic.HashSet[string]]::new([string[]]$empList.UserPrincipalName, [StringComparer]::OrdinalIgnoreCase)
$NotInList = $arrayEmail |Where-Object { -not $empListEmail.Contains($_) }
CodePudding user response:
If you don't mind having unique emails in $arrayEmail
this is a similar take on Mathias's answer but reversing the order for the HashSet<T>
and using it's .ExceptWith
Method for filtering.
$arrayEmail = [System.Collections.Generic.HashSet[string]]::new(
[string[]] $array.Email.Trim(),
[StringComparer]::OrdinalIgnoreCase
)
$arrayEmail.ExceptWith([string[]] $empList.UserPrincipalName)
$arrayEmail # => updated to only values not in `$empList.UserPrincipalName`