Alot of Straw
Alot of Straw

Reputation: 23

Comparing Arrays in Powershell

There is probably a simple way to do this, but I've been hitting my head against a wall for hours at this point. I'm trying to grab several user attributes out of AD, compare two of those attributes, and then modify them based on the differences. However since some users have null values for either their office or department fields which causes compare-object to fail, I have those going into other arrays with a -replace to get rid of the nulls, so my variables look like this:

$UserData = Get-ADuser -filter * -properties physicaldeliveryofficename,department | select samaccountname,physicaldeliveryofficename,department
$Offices = $UserData.physicaldeliveryofficename -replace "^$","N/A"
$Departments = $UserData.department -replace "^$","N/A"

So far so good, but when I loop through to compare values, I start to run into trouble. Looping through the users like this seems to be comparing every element to every other element:

Foreach ($user in $UserData.samaccountname) {
Compare-object $offices $departments -includeqeual}

While not having a loop and using compare-object by itself gives accurate results, but then I'd need a loop to check for matches anyway.

Assuming I just want to determine which users have matching office and department fields (and based off that do a pretty simple Set-ADUser command), how would I go about comparing the values without checking every element against every other element?

Upvotes: 2

Views: 1408

Answers (1)

boeprox
boeprox

Reputation: 1868

Your ForEach loop won't work properly because even though you are going through each user account, you are always comparing the same collection of offices and departments. I wrote this that might give you better results and saves the compare results as part of an object so you can see the user account as well.

Get-ADuser -Filter * -properties physicaldeliveryofficename,department | ForEach {
    $Offices = $_.physicaldeliveryofficename -replace "^$","N/A"
    $Departments = $_.department -replace "^$","N/A"
    $Results = Compare-object $offices $departments -IncludeEqual
    [pscustomobject]@{
        User = $_.samaccountname
        compare = $Results
    }
}

Upvotes: 2

Related Questions