我最近在PowerShell上观看了一些CBT掘金队,其中一位教练表示,首先使用ForEach-Object
和cmdlets
,使用WMI Methods
应该是最后的选择。那么,我的问题是从同一类型的多个对象获取属性的最有效方法是什么?例如:
会这样:
(Get-ADComputer -Filter *).Name
比这更有效:
Get-ADComputer -Filter * | ForEach-Object {$_.Name}
这些功能如何相互不同?
答案 0 :(得分:1)
#This is compatible with PowerShell 3 and later only
(Get-ADComputer -Filter *).Name
#This is the more compatible method
Get-ADComputer -Filter * | Select-Object -ExpandProperty Name
#This technically works, but is inefficient. Might be useful if you need to work with the other properties
Get-ADComputer -Filter * | ForEach-Object {$_.Name}
#This breaks the pipeline, but could be slightly faster than Foreach-Object
foreach($computer in (Get-ADComputer -Filter *) )
{
$computer.name
}
我通常坚持使用Select-Object -ExpandProperty以确保兼容性。
干杯!