1

The following code I have is fetching data from SQL however the -ne operator is not working correctly when I have more than one object in $teamConfig.

The following Code outputs the following:

$teamConfig = @(
    [pscustomobject]@{
        TeamName  = 'Team1'
        TeamEmail = 'team1@domain.tld'
    }
    [pscustomobject]@{
        TeamName  = 'Team3'
        TeamEmail = 'team1@domain.tld'
    }
)

$query = "select * from INCAutomation"

$results = Invoke-Sqlcmd -query $query -ServerInstance 'localhost' -Database 'AyushTest'

foreach ($item in $teamConfig) {
    $teamsExcluded = $results | Where-Object TeamName -ne $item.TeamName | Select TeamName
}

$teamsExcluded

Result:

TeamName
--------
Team1
Team1
Team1
Team1
Team2
Team2
Team2

After removing Team3 from the $teamConfig (example) I get the following desired output:

$teamConfig = @(
    [pscustomobject]@{
        TeamName  = 'Team1'
        TeamEmail = 'team1@domain.tld'
    }
)

$query = "select * from INCAutomation"

$results = Invoke-Sqlcmd -query $query -ServerInstance 'localhost' -Database 'AyushTest'

foreach ($item in $teamConfig) {
    $teamsExcluded = $results | Where-Object TeamName -ne $item.TeamName | Select TeamName
}

$teamsExcluded

Result:

TeamName
--------
Team2
Team2
Team2

I've been stuck on this one for a little while, thanks in advance!

Ken White
  • 123,280
  • 14
  • 225
  • 444
yush
  • 365
  • 9
  • 26

1 Answers1

1

Use a single pipeline with the -notIn operator, combined with member-access enumeration, in which case you don't need a foreach loop:

$teamsExcluded = $results | 
  Where-Object TeamName -notin $teamConfig.TeamName | 
    Select TeamName

The above is not only more efficient, it also avoids the logical problem with your solution attempt: you filtered the full collection, $results, in each foreach loop iteration, instead of filtering cumulatively (excluding Team1 first, and then excluding Team3 from that already filtered list). In effect, only the last team specified, Team3, was therefore excluded from the list.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thanks heaps! That works perfectly, however for some reason its not letting me iterate over $teamsExcluded (using foreach). I need to to be able to do that so I can insert individual HTML tags to each value - any ideas? – yush Jan 06 '21 at 03:55
  • Thanks a lot for this again, I had a mind blank before but this works perfectly – yush Jan 06 '21 at 04:05
  • Glad to hear it, @ayushlal; my pleasure. – mklement0 Jan 06 '21 at 04:14