【发布时间】:2016-03-05 03:35:57
【问题描述】:
作为一名 C# 开发人员,我仍在学习 PowerShell 的基础知识并且经常感到困惑。 为什么 $_.给我第一个示例中有效属性名称的智能感知列表,而不是第二个示例?
Get-Service | Where {$_.name -Match "host" }
Get-Service | Write-Host $_.name
这两个例子的基本区别是什么?
当我运行第二个时,它在 Get-Service 的每次迭代中都会出现此错误:
Write-Host : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters
that take pipeline input.
At line:3 char:15
+ Get-Service | Write-Host $_.name
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (wuauserv:PSObject) [Write-Host], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.WriteHostCommand
我和我的同事首先使用一个 foreach 循环来迭代一个 Get-commandlet,但我们却无法让属性名称出现。我们试图简化,直到我们进入上面的核心基础。
只是发现有时这是命令行开关中的拼写错误,下面的第一个错误是因为命令行开关应该是 Get-Service 而不是 Get-Services。
foreach ($item in Get-Services)
{
Write-Host $item.xxx #why no intellisense here?
}
foreach ($item in Get-Service)
{
Write-Host $item.Name
}
【问题讨论】:
-
仅供参考:
Get-Service | Select -Expand Name让这变得简单多了。如果您只想从一系列事物中获取一个属性的值,Select -Expand 非常适合扩展该属性的值并为每个对象返回该值。 -
为了使 BatekB 的解释更简单,这是因为您没有通过管道连接到 for-each 循环:
get-service | % { Write-host $_.Name }将起作用 -
@Cole9350 - 你的 cmets 听起来是我的最佳答案 - 为什么不把它放在下面的答案中,我会选择它。
-
@Neal 我相信 bartek 涵盖了所有基础并在技术上进行了最佳解释
标签: powershell