Search code examples
powershellpowershell-3.0powershell-4.0powershell-remotingpowershell-cmdlet

Parsing not working correctly for Powershell


I have written the following logic to check status of service:

$status=@()

if($var1 -match "True") {
Write-Output "Service Enabled"
} else {
$status+="Service not Enabled"
Write-Output "Service not Enabled"
}

if($status.count -le 1){
    $returnStatus = "PASS"    
}else{
    $o=$status -join ", "
    $returnStatus = "FAIL- $o"
}

$getstatus = $returnStatus 

When, I set $var1 = false the output should be Service not Enabled but it is not correct.

It seems that the issue is with $status always having a count of 1even when it is PASS Please suggest if there is a better logic to do the same logic.


Solution

  • You have a typo in the variable name $returnsStatus / $returnStatus

    Which causing final output $getstatus inconsistent.

    Please fix variable name and try again.

    Proposed Solution

    $status=@()
    
    if($var1 -match "True") {
        Write-Output "Service Enabled"
    } else {
        $status+="Service not Enabled"
        # Fixed Message
        Write-Output "Service not Enabled"
    }
    
    # Fix comparison from -le to -lt
    if($status.count -lt 1){
        $returnStatus = "PASS"    
    }else{
        $o=$status -join ", "
        $returnStatus = "FAIL- $o"
    }
    
    $getstatus = $returnStatus