2012-08-09 5 views
6

해결 방법 :파이프 입력에서 읽는 powershell 함수는 어떻게 작성합니까?

다음은 파이프 입력을 사용하는 함수/스크립트의 가장 간단한 가능한 예입니다. 각각은 "echo"cmdlet으로 파이핑하는 것과 동일하게 작동합니다.

으로 기능 : 스크립트로

Function Echo-Pipe { 
    Begin { 
    # Executes once before first item in pipeline is processed 
    } 

    Process { 
    # Executes once for each pipeline object 
    echo $_ 
    } 

    End { 
    # Executes once after last pipeline object is processed 
    } 
} 

Function Echo-Pipe2 { 
    foreach ($i in $input) { 
     $i 
    } 
} 

:

# 에코 Pipe.ps1
Begin { 
    # Executes once before first item in pipeline is processed 
    } 

    Process { 
    # Executes once for each pipeline object 
    echo $_ 
    } 

    End { 
    # Executes once after last pipeline object is processed 
    } 
# 에코 Pipe2.ps1
foreach ($i in $input) { 
    $i 
} 

일예

function set-something { 
    param(
     [Parameter(ValueFromPipeline=$true)] 
     $piped 
    ) 

    # do something with $piped 
} 

하나의 매개 변수가 파이프 라인 입력에 직접 결합 될 수 있음을 명백해야한다 :

PS > . theFileThatContainsTheFunctions.ps1 # This includes the functions into your session 
PS > echo "hello world" | Echo-Pipe 
hello world 
PS > cat aFileWithThreeTestLines.txt | Echo-Pipe2 
The first test line 
The second test line 
The third test line 

답변

12

는 또한 고급 기능을 사용하는 옵션 대신 위의 기본적인 접근 방식을 가지고있다. 그러나 여러 매개 변수가 파이프 라인 입력에 서로 다른 속성에 바인딩 할 수 있습니다 :이 다른 쉘을 배울 수있는 당신의 여행에 당신을 도와줍니다

function set-something { 
    param(
     [Parameter(ValueFromPipelineByPropertyName=$true)] 
     $Prop1, 

     [Parameter(ValueFromPipelineByPropertyName=$true)] 
     $Prop2, 
    ) 

    # do something with $prop1 and $prop2 
} 

희망을.

관련 문제