Home > Software engineering >  Where object as variable
Where object as variable

Time:11-12

After reading many of the posted solutions here, none fully applies mine. This works (returns expected number of instancesNames based on criteria):

$response.result | Where-Object {$_.targetType -eq "webserver" -and ($_.agentHostName -eq "ServerA" -or $_.agentHostName -eq "ServerB")} | select-Object "instanceName"

However, since n number of servers may be found, I created a loop to dynamically create this query:

    [System.Text.StringBuilder]$clause = " {`$_.targetType -eq ""webserver"" -and (" 
    $i = 1;
    foreach ($server in $serversArray) {
    
        if ( $i -eq $serversArray.Count ) {
            $clause.Append("`$_.agentHostName -eq ""${server}"")}")
        } else {
            $clause.Append( "`$_.agentHostName -eq ""${server}"" -or ")
        }   
        $i  
    }
    $clause.Append(" | select-Object ""instanceName""")

$filter = [scriptblock]::Create($clause)
$instances = $response.result | where-object $filter 

debugging: the $clause variable contains:

{$_.targetType -eq "webserver" -and ($_.agentHostName -eq "serverA" -or $_.agentHostName -eq "serverB")} | select-Object "instanceName"

However, it returns all instanceNames (not filtered) instead of the ones that meet the criteria. What am I doing wrong here?

CodePudding user response:

The -in operator would simplify your code. For example:

$response.result | 
    Where-Object {($_.targetType -eq 'webserver') -and ($_.agentHostName -in $serversArray)} |
    Select-Object 'instanceName'
  • Related