Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where-object $_ matches multiple criterias

Tags:

powershell

$data|where-object{$_.Name -eq "$serverName.domain.com"}|select-object -Property Description1, Version | where-object{$_.Description1 -match "bnx2x" -or "be2net"} | %{"{0}" -f $_.Version}

So I'm trying to get the version number. However, the Description1 can have two names that I want to look for. I've gotten my code to work for just matching one string but I cant seem to find the right syntax to match multiple strings with an "-or"

like image 223
runcmd Avatar asked May 27 '14 18:05

runcmd


People also ask

Where-Object notlike?

where-object -notlike from TechNet: Specifies the Not-Like operator, which gets objects when the property value does not match a value that includes wildcard characters.

Where-Object cmdlet is used to__________?

The Where-Object cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.

How do I match multiple values in PowerShell?

Use the string Join method to join the multiple values with | ( or). The PowerShell match operator uses the string value joined by the | operator to check if the given string contains multiple values.

Where-Object filters?

In a nutshell, the Where-Object cmdlet is a filter; that's it. It allows you to construct a condition that returns True or False. Depending on the result of that condition, the cmdlet then either returns the output or does not.


1 Answers

This should do what you want, and is a bit shorter than what you originally had.

$data | Where-Object{
  $_.Name -eq "$serverName.chrobinson.com" -and (
     $_.Description1 -match "bnx2x" -or
     $_.Description1 -match "be2net"
  )
} | Select-Object -expand version

You just needed $_.Description1 -match "bnx2x" -or $_.Description1 -match "be2net" really, but I think this is easier to read than what you had.

like image 59
TheMadTechnician Avatar answered Oct 07 '22 00:10

TheMadTechnician