我正在尝试计数命令输出的一些行。在这个例子中,基本上所有以"Y"结尾的行。
拳头捕获命令结果:
PS> $ItsAgents = tacmd listSystems -n Primary:SomeHost:NT
PS> $ItsAgents
Managed System Name Product Code Version Status
Primary:SomeHost:NT NT 06.30.07.00 Y
SomeHost:Q7 Q7 06.30.01.00 N
现在计算在线的:
PS> $AgentCount = ($ItsAgents | Select-String ' Y ').Count
PS> $AgentCount
1
现在一切如我所料。所以我把它放在我的脚本中,就像这样:
$ItsAgents = tacmd listSystems -n $agent
Write-Host $ItsAgents
$BeforeCount = ($ItsAgents | Select-String ' Y ').Count
当脚本运行时(在Set-StrictMode
下(,我得到:
The property 'Count' cannot be found on this object. Verify that the
property exists.
At Y:ScriptsnewMoveAgents.ps1:303 char:7
+ $BeforeCount = ($ItsAgents | Select-String ' Y ').Count
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
Write-Host
确实输出了正常的结果,因此$agent
设置正确,并且tacmd
命令运行正常那么,为什么它在脚本中失败,却在命令行中工作呢?
使用@()
运算符强制输出始终为数组:
$BeforeCount = @($ItsAgents | Select-String ' Y ').Count
数组子表达式运算符创建一个数组,即使它包含零个或一个对象。(Microsoft文档(
注意:Afaik应该以与脚本和控制台相同的方式工作。也许您的命令会产生不同的输出,控制台版本会返回2+个结果,但由于某种原因,脚本版本只返回1或0个结果,这就是没有Count
属性的原因