Powershell 파이프라인은 사용자 편의와, 웃기지만 “일관성”을 위해 컬렉션을 “풀어” 줘요. 단항 연산자는 powershell이 그렇게 풀지 못하게 해요. 그 예제들은 썩 좋지 않으니 다른 방식으로 해 볼게요.
다음 두 코드의 출력을 보세요
(4, 5, 6) | ForEach-Object {
Write-Host "Pipeline element now: $_"
}
Pipeline element now: 4
Pipeline element now: 5
Pipeline element now: 6
,(4, 5, 6) | ForEach-Object {
Write-Host "Pipeline element now: $_"
}
Pipeline element now: 4 5 6
뒤쪽 예제는 컬렉션 전체를 한 객체로 보내서 풀리지 않아요. 실제로 배열이고, 쉼표 대신 공백이 보이는 건 기본 출력 필드 구분자가 공백이기 때문이에요($ofs에 들어 있어요). 이렇게 확인할 수 있어요
"$(4, 5, 6)"
4 5 6
문자열 안에 배열을 넣으면 powershell이 기본 OFS로 원소들을 이어 붙여요. 바꿀 수도 있지만 그럴 일은 드물어요.
$ofs = '/~/'
"$(4, 5, 6)"
4/~/5/~/6
제가 이 단항 연산자를 꽤 자주 쓰는 경우는 값들을 나누되 모든 원소를 한 객체 안에 함께 담아 보내고 싶을 때예요.
,(-split 'Tavin enjoys powershell') | ForEach-Object {
[PSCustomObject]@{
Who = $_[0]
Does = $_[1]
Topic = $_[2]
}
}
Who Does Topic
--- ---- -----
Tavin enjoys powershell
영어에서 번역·원문 보기The Powershell pipeline “unwraps” collections for convenience and, amusingly, for user “consistency”. That unary operator stops powershell from performing that unwrapping. Those examples aren't ideal, so I'll try another approach.
Look at what these two snippets produce
(4, 5, 6) | ForEach-Object {
Write-Host "Pipeline element now: $_"
}
Pipeline element now: 4
Pipeline element now: 5
Pipeline element now: 6
,(4, 5, 6) | ForEach-Object {
Write-Host "Pipeline element now: $_"
}
Pipeline element now: 4 5 6
The latter sends the complete collection through as a single object, so it never gets unwrapped. It's an array, and the spaces you see, rather than commas, come from the space used as the default output field separator (held in $ofs). Here's a way to observe that
"$(4, 5, 6)"
4 5 6
Embedding that array in a string makes powershell join its elements using the default OFS. Changing it is possible, although seldom necessary.
$ofs = '/~/'
"$(4, 5, 6)"
4/~/5/~/6
One fairly frequent use for that unary operator in my own work is splitting values while keeping every element together in a single object.
,(-split 'Tavin enjoys powershell') | ForEach-Object {
[PSCustomObject]@{
Who = $_[0]
Does = $_[1]
Topic = $_[2]
}
}
Who Does Topic
--- ---- -----
Tavin enjoys powershell