Tchotchke
Tchotchke

Reputation: 399

Get other data from object using Where-Object

I have two collections of objects, A and B. A is from a CSV file and B is from Get-ADUser. Both A and B have a field named "Username". What I want to be able to do is check if B contains A, and if so, copy the description from B into A. Something like this:

$A.'Description' = $B | ? {$A.Username -eq $B.Username; $B.Description}

I feel like there is a way to do this without iterating across another loop (I'm already looping through each obj in A).

Upvotes: 1

Views: 237

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Create a hashtable mapping the usernames from $B to the respective descriptions:

$ht = @{}
$B | ForEach-Object { $ht[$_.Username] = $_.Description }

Then iterate over the elements of $A and update those descriptions if $ht contains a matching key:

$A | Where-Object {
    $ht.ContainsKey($_.Username)
} | ForEach-Object {
    $_.Description = $ht[$_.Username]
}

Upvotes: 1

Related Questions