2014-03-31 8 views
1

저는 최근에 PowerShell에서 CBT Nuggets를 보았습니다. 그 중 하나에서 강사는 ForEach-Object을 활용하면 최후의 수단으로 cmdletsWMI Methods을 사용할 수 있다고 말합니다. 그래서, 내 질문은 같은 유형의 여러 개체에서 속성을 얻는 가장 효율적인 방법은 무엇입니까? 예를 들어 :PowerShell의 개체 배열에서 속성에 액세스하는 가장 효율적인 방법은 무엇입니까?

이 것 :

(Get-ADComputer -Filter *).Name 

이보다 더 효율적 :

Get-ADComputer -Filter * | ForEach-Object {$_.Name} 

어떻게 서로 다르게 이러한 기능을합니까?

+0

일반적인 규칙은 cmdlet에서 필터링을 허용하면 사용하는 것이 좋습니다. 이렇게하면 파이프 라인에 필요하지 않은 물건들을 넣지 않아도됩니다. 명령을 입력 할 때 필터링을 가능한 한 "왼쪽"까지 밀어 넣습니다 (즉, ForEach-Object 또는 Select-Object에 대한 cmdlet 기본 제공 필터링을 선호 함) –

답변

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를 사용합니다.

건배!

관련 문제