11.1 Making the shell give you just what you need
11.2 Filtering left
把过滤条件尽可能放到靠左的位置,因为这样可以减少后面的命令的工作量。
filter-left
的缺点是每个cmdlet都可以实现自己指定的过滤方式,这给我们的记忆带来不便。比如, Get-Service
只能过滤 -name
属性。而对于 Get-ADComputer
,我们可以对任何 Computer
对象可能有的 Active Direc-tory
进行过滤。
如果某个cmdlet不能满足我们想要过滤的要求,我们可以使用 Where-Object
(别名Where
)。该cmdlet使用通用的语法,我们可以使用它过滤任何对象。
11.3 Using comparison operators
PowerShell的比较默认是不区分大小写的。
我们可以使用 $_
占位符来代替pipeline中的对象。
使用 $True
和 $False
来表示布尔值 True
和 False
11.4 Filtering objects out of the pipeline3
如果我们想要保留正在运行中的服务,可以使用:
Get-Service | Where-Object -filter { $_.Status -eq 'Running' }
想要添加更多限制条件,可以:
get-service | where-object {$_.status -eq 'running' -AND $_.StartType -eq 'Manual'}
11.6 Common points of confusion
11.6.1 Filter left, please
我们过滤的准则是 : go as close to the beginning of the command line as possible.
11.6.2 When $_ is allowed
The special
$_
placeholder is valid only in the places where PowerShell knows to look for it.
When it’s valid, it contains one object at a time from the ones that were piped into that cmdlet.
Keep in mind that what’s in the pipeline can and will change throughout the pipeline, as various cmdlets execute and produce output.