johnfli
johnfli

Reputation: 3

if/elseif not working right

I have a script that checks how much memory the top w3wp process is using. Then depending on how close to 1 gig it is using, it will give out a message.

param($warn, $crit)
$LastExitCode = 3
$Output1 = ""
$output = ""
$myW3WP = Get-Process w3wp | Sort -Descending WS | select -first 1 |
          Measure-Object WS -Sum 
$myW3WP = ("{0:N2} " -f ($myW3WP.sum / 1mb))
$myW3WP.trim()
if ($myW3WP -gt $crit) {
    $LastExitCode = 2
    $output1 = "CRITICAL: Memory for W3WP has passed 1 gig $myW3WP"
    $output = $output1
} elseif ($myW3WP -gt $warn) {
    $LastExitCode = 1
    $output1 = "WARN: Memory for W3WP is getting close to 1 gig $myW3WP"
    $output = $output1
} else {
    $LastExitCode = 0
}

$output = $output1
Write-Host $output $LastExitCode "$myW3WP >= " $crit  ($myW3WP -gt $crit) "$myW3WP >= " $warn ($myW3WP -gt $warn)
$myW3WP = ""

In values for $crit is 1000 and the value for $warn is 900. (Note: the Write-Host line is like that for troubleshooting)

Here is the output I am getting:

CRITICAL: Memory for W3WP has passed 1 gig 161.03 2 161.03 >= 1000 True 161.03 >= 900 False

The 161.03 is the megs of RAM being used.

Any ideas on why it is saying 161.03 is greater than 1000?

Upvotes: 0

Views: 439

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Don't compare apples and oranges!

You'll need a numerical value if you want to compare it to other numerical values

When you call:

$myW3WP = ("{0:N2} " -f ($myW3WP.sum / 1mb))
$myW3WP.trim()

you create a string.

Replace those two lines with just:

$myW3WP = $myW3WP.Sum / 1MB

And it'll work

Upvotes: 2

Sean
Sean

Reputation: 62472

$myW3WP is a string, not a number, so you're doing a textual comparison, rather than a numeric one. The line:

$myW3WP = ("{0:N2} " -f ($myW3WP.sum / 1mb))

Is what forces the variable to be a string. Just leave it as a number and don't worry about the decimal places:

$myW3WP = $myW3WP.sum / 1mb

Upvotes: 1

Related Questions