2014-10-11 3 views
2

아래 두 코드 간의 차이점을 이해할 수 있습니까? 결과가 둘 다 다른 이유는 무엇입니까? 나는 각각의 경우 내가 동일한 속성을 선택하고 (이름) :선택 개체와 동일한 개체에서 foreach를 사용하는 것의 차이점

코드 1 :

$obj = Get-Service | Where-Object {$_.Status -eq "Running"} | foreach-object {$_.Name} | select -first 3 
foreach ($item in $obj) { write-output "Name is : $item" } 
Output : 
Name is : AeLookupSvc 
Name is : Appinfo 
Name is : AudioEndpointBuilder 

코드 2 :

$obj = Get-Service | Where-Object {$_.Status -eq "Running"} | select -first 3 name 
foreach ($item in $obj) { write-output "Name is : $item" } 
Output : 
Name is : @{Name=AeLookupSvc} 
Name is : @{Name=Appinfo} 
Name is : @{Name=AudioEndpointBuilder} 

답변

6

Select-Object는 사용자 지정 개체의 배열을 파이프 라인에 반환합니다. 이 경우에는 하나의 속성 만 문자열이됩니다.
@walidtourni에 언급 된 바와 같이 expand을 사용하면이 문제를 해결할 수 있습니다. expand은 해당 값을 가진 속성이있는 사용자 지정 개체 대신 출력이 속성의 값이되기 때문입니다. 이것이 가능한 이유는 expand은 하나의 인수 만 취합니다. 즉, 동일한 "행"에 대해 여러 값을 반환하려고 시도 할 가능성이 없습니다.

반면에 foreach-object는 단순히 파이프 라인에 물건을 뱉어내는 것입니다. 사용자 지정 개체에 둘 다 수동으로 래핑하지 않고 두 번째 속성을 포함하려고하면 동일한 행에 두 개의 속성 대신 다른 행이 만들어집니다.

Clear 
$x = Get-Service | Where-Object {$_.Status -eq "Running"} | select -first 3 
$x | foreach-object {$_.Name} #returns 3 rows, single column; string 
$x | foreach-object {$_.Name,$_.CanPauseAndContinue;} #returns 6 rows, single column; alternate string & boolean 
$x | foreach-object {$_.Name;$_.CanPauseAndContinue;} #returns 6 rows, single column; alternate string & boolean 
$x | select Name #returns 3 rows, single column (string); custom object 
$x | select Name, CanPauseAndContinue #returns 3 rows, two columns (string & boolean); custom property 
$x | select -expand Name #returns 3 rows, single column; string; notice the lack of column header showing this is a string, not a string property of a custom object 
$x | select -expand Name,CanPauseAndContinue #error; -expand can only take single valued arguments 
$x | select -expand Name -expand CanPauseAndContinue #error; you can't try to define the same paramenter twice 
+1

설명에 감사드립니다. 정말 도움이되었습니다. –

+1

@SubhayanBhattacharya 감사의 말을 나타내는 가장 좋은 방법은 John의 답을 정확하다고 표시하는 것입니다. – Matt

2

비슷한 결과를 들어이 같은 두 번째 예제를 변경할 수 있습니다

select -first 3 -expand name 

개체 선택 개체 선택

+1

이 두 조각이가 OP 같은 차이가 요구되었다 설명하지 않습니다 같은 일을한다하더라도 :

다음과 같은 실행, 증명합니다. 더 자세한 답변을 적어주십시오. – Matt

관련 문제