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
这是常见的PowerShell问题.命令可以返回:
Count,让它获取null或失败)Count属性,最令人困惑的情况 - 可以返回任何内容;或者可能没有它,然后Count获取null或失败)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)
| 归档时间: |
|
| 查看次数: |
5652 次 |
| 最近记录: |