Compare the three scripts below:
Sample 1
$a = GPS | Where {$_.ProcessName -Match 'AcroRd32'}
$a
$a.Count
If ($a.Count -Eq 0)
{
Echo "Adobe Reader is Off"
}
Else
{
Echo "Adobe Reader is On"
}
# If Adobe Reader is not running, how come 0 (zero) is not returned?
# This is prettier, should I use it? Or does it slow down performance?
Sample 2
$a = GPS AcroRd32
$a
$a.Count
If ($a.Count -Eq 0)
{
Echo "Adobe Reader is Off"
}
Else
{
Echo "Adobe Reader is On"
}
# If Adobe Reader is not running, how come 0 (zero) is not returned?
# This is uglier, but it doesn't have to pipe any output, so does it have any performance gains?
Sample 3
GPS AcroRd32 | Measure | Select -Expand Count
# 0 (zero) is returned, but with an ugly Error
I guess part of my problem is that I'm treating PowerShell like it's VBS; writing code in this manner/style would usually yield me an integer value of zero and not throw any errors (if Adobe Reader was off, of course). What's the correct PowerShell way of checking that an instance of a program is not running? The performance questions in the comments are secondary to the "PowerShell Way" question.
P.S. To be honest, the Error Message returned by the 3rd Sample wouldn't break anything, it's just ugly, so it's not beyond practical use, so I guess the real problem is that I'm just a sucker for aesthetics =^D
This is a common PowerShell gotcha. A command can return:
Count
, getting it either gets null or fails)Count
property, the most confusing case -- can return anything; or may not have it, then getting Count
gets null or fails)Count
.The solution is simple. When you really need the count of returned objects use the @()
operator. The result is always an array which has the property Count
.
# this is always an array
$result = @(<command returning something or nothing>)
# this is always a number:
$result.Count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With