Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if an string exists in a list of strings, using powershell

Tags:

powershell

I have Powershell version 3,4 and 5 in my environment. When I write below code it continously gave me false, though $CompatiableOS contains output of $OSverions.

   [string] $CompatiableOS = '2016','2012','2008'
   $OSVersion=[regex]::Matches(((Get-WmiObject -class Win32_OperatingSystem).caption), "([0-9]{4})")

   if ( $CompatiableOS -contains  $OSVersion)
   {
      return $TRUE
   }
   else
   {
      return $FALSE
   }

but when I changed above code to below, it worked. What could be the issue?

 [string] $CompatiableOS = '2016','2012','2008'
 $OSVersion=[regex]::Matches(((Get-WmiObject -class Win32_OperatingSystem).caption), "([0-9]{4})")

 if ( $CompatiableOS.contains($OSVersion))
 {
    return $TRUE
 }
 else
 {
      return $FALSE
 }
like image 712
coolRV Avatar asked Jul 08 '19 08:07

coolRV


1 Answers

This comes up a lot. -contains vs .contains(). They're very different. -contains has to match exactly. But the left side can be an array of strings. You actually joined everything into one string on the left with the [string] cast.

$compatibleos
'2016 2012 2008'

'2016 2012 2008' -contains '2016'
False

'2016 2012 2008'.contains('2016')
True

'2016','2012','2008' -contains '2016'
True

('2016','2012','2008').contains('2016')
True
like image 95
js2010 Avatar answered Oct 12 '22 02:10

js2010