Search code examples
powershellconditional-statementslogicpowershell-2.0

What is wrong with this if condition in powershell?


i am trying to find the service running, also checking the right version and above is there in my machine if yes , then i need to return 1 else zero

I need to check

Condition 1 : $servicestatus = true

OR

Condition 2 : Where Status -ne "Running" = true

AND

Condition 3 : Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Where-Object {$.DisplayName -like "Crow*" -and $.DisplayVersion -gt 6.28} command should have atleast 1 record

Then exit 1

if no record in condition 3 then exit 0

Issue

But when

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Where-Object {$.DisplayName -like "Crow*" -and $.DisplayVersion -gt 6.28} result having a record or not, then entire code is resulting 1

But I am expecting zero when no records have resulted in a third condition.

Please help: here is the full code i written

$servicestatus = get-service 'something'
If (@($servicestatus | Where Status -ne "Running" | Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Where-Object {$_.DisplayName -like "Crow*" -and $_.DisplayVersion -gt 6.28}).Count -gt 0)
    {
        echo "1"
       Exit 1
       
    }
Else
    {
        echo "1"
       Exit 0
    }

I modified code to add an and condition but still no luck

$servicestatus = get-service 'something'
If (@(($servicestatus | Where Status -ne "Running" ) -and (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate  | Where {($_.DisplayName -like "Crow*") -and ($_.DisplayVersion -gt 6.28)})).Count -gt 0)
    {
        echo "1"
       Exit 1
       
    }
Else
    {
        echo "1"
       Exit 0
    }

Solution

  • It's sometime weird but you may want to set every condition separated by -and, -or and so on in brackets, like this:

    | Where {($_.DisplayName -like "Crow*") -and ($_.DisplayVersion -gt 6.28)}
    

    As far as I know the reason is that powershell thinks that -and is a parameter of a previous expression (string in this example).

    To edited code:

    Try this instead:

    if(($servicestatus.Status -ne "Running") -and ((Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Where-Object {($_.DisplayName -like "Crow*") -and ($_.DisplayVersion -gt 6.28)}).Count -gt 0))