Comparison Operators

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Lery Lery 2 years ago.

  • Author
    Posts
  • #20535
    Profile photo of Lery
    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
    Profile photo of Richard Siddaway
    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
    Profile photo of Lery
    Lery
    Participant

    Thanks Richard. Appreciate the fast response.

You must be logged in to reply to this topic.