Comparison Operators

This topic contains 2 replies, has 2 voices, and was last updated by  Lery 2 years, 10 months ago.

  • Author
    Posts
  • #20535

    Lery
    Participant

    Here is my code:

    $b = Get-WmiObject -Class Win32_LocalTime  | Select-Object -ExpandProperty Hour
    if ($b -contains 15 -or 16 -or 17){
        Write-Host "Time equals $b" -ForegroundColor Yellow}
    

    $b has the value of 14. My comparison operation is evaluating to True and writing host. I'm hitting my head against the desk here!

    The goal is if the hour returned is between 15, 16, or 17, do something. If not, do nothing.

  • #20537

    Richard Siddaway
    Moderator

    You can't use contains like that

    Either do this

    $b = Get-WmiObject -Class Win32_LocalTime | Select-Object -ExpandProperty Hour
    if ($b -ge 15 -and $b -le 17){
    Write-Host "Time equals $b" -ForegroundColor Yellow
    }
    else {
    Write-Host "$b is out of range"
    }

    OR if you want to use -contains
    $h = 15..17
    $b = Get-WmiObject -Class Win32_LocalTime | Select-Object -ExpandProperty Hour
    if ($h -contains $b){
    Write-Host "Time equals $b" -ForegroundColor Yellow
    }
    else {
    Write-Host "$b is out of range"
    }

  • #20539

    Lery
    Participant

    Thanks Richard. Appreciate the fast response.

You must be logged in to reply to this topic.