如何使用Get-Process中的Count属性返回漂亮的零值?

Sti*_*sfa 5 powershell stderr powershell-2.0

比较下面的三个脚本:

样品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?
Run Code Online (Sandbox Code Playgroud)



样本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?
Run Code Online (Sandbox Code Playgroud)



样本3

GPS AcroRd32 | Measure | Select -Expand Count

# 0 (zero) is returned, but with an ugly Error
Run Code Online (Sandbox Code Playgroud)



我想我的部分问题是我将PowerShell视为VBS; 以这种方式/样式编写代码通常会产生一个整数值为零而不会抛出任何错误(当然,如果Adobe Reader已关闭).什么是检查程序实例未运行的正确 PowerShell方法?评论中的性能问题是"PowerShell Way"问题的次要问题.

PS老实说,第三个样本返回的错误信息不会破坏任何东西,它只是丑陋,所以它不会超出实际用途,所以我猜真正的问题是我只是一个美学的吸盘= ^ D

Rom*_*min 8

这是常见的PowerShell问题.命令可以返回:

  • 没有〜null(没有属性Count,让它获取null或失败)
  • 单个对象(它可能有自己的属性Count属性,最令人困惑的情况 - 可以返回任何内容;或者可能没有它,然后Count获取null或失败)
  • 2+具有该属性的对象数组Count.

解决方案很简单.当您确实需要返回对象的计数时,请使用@()运算符.结果始终是具有该属性的数组Count.

# this is always an array
$result = @(<command returning something or nothing>)

# this is always a number:
$result.Count
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果你选择`@(GPS AcroRd32)`那么当过程不存在时就准备好了.如果错误偏好为*Stop*,则错误会很慢或可能会失败.为避免错误,您可以使用此技巧:http://stackoverflow.com/questions/4362275/powershell-check-if-item-exists-without-an-error-if-it-doesnt/4364807#4364807.然后`@(GPS [A] croRd32)`应该是性能最好的. (2认同)