Comparison Operators

Welcome Forums General PowerShell Q&A Comparison Operators

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
4 years, 9 months ago.

  • Author
    Posts
  • #20535

    Participant
    Topics: 25
    Replies: 56
    Points: 2
    Rank: Member

    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

    Participant
    Topics: 0
    Replies: 669
    Points: 0
    Rank: Member

    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

    Participant
    Topics: 25
    Replies: 56
    Points: 2
    Rank: Member

    Thanks Richard. Appreciate the fast response.

The topic ‘Comparison Operators’ is closed to new replies.