从PowerShell中的对象数组访问属性的最有效方法是什么?

从PowerShell中的对象数组访问属性的最有效方法是什么?,powershell,performance,Powershell,Performance,最近,我在PowerShell上观看了一些CBT掘金,其中一位讲师说,首先使用可用的cmdlet和WMI方法,使用ForEach对象应该是最后的选择。所以,我的问题是,从同一类型的多个对象获取属性的最有效方法是什么?例如: 请问: (Get-ADComputer -Filter *).Name 要比这更有效率: Get-ADComputer -Filter * | ForEach-Object {$_.Name} 这些功能之间有什么不同 #This is compatible with Po

最近,我在PowerShell上观看了一些CBT掘金,其中一位讲师说,首先使用可用的
cmdlet
WMI方法,使用
ForEach对象
应该是最后的选择。所以,我的问题是,从同一类型的多个对象获取属性的最有效方法是什么?例如:

请问:

(Get-ADComputer -Filter *).Name
要比这更有效率:

Get-ADComputer -Filter * | ForEach-Object {$_.Name}
这些功能之间有什么不同

#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
    }
我通常坚持选择Object-ExpandProperty以确保兼容性


干杯

我认为一般的规则是,如果cmdlet允许您进行筛选,那么您应该使用它。这避免了将一堆你不需要的东西放入管道中。键入命令时,尽可能将任何筛选推到“左侧”(即,与ForEach对象或Select对象相比,更喜欢cmdlet内置筛选)以提高流程的效率,您应该查看整个解决方案,因为完整(PowerShell)解决方案的性能应优于其各部分的总和,另见: