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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With