2012-08-09 3 views
6

解説:パイプ入力から読み込むpowershell関数をどのように記述しますか?

以下は、パイプ入力を使用する関数/スクリプトの最も単純な例です。それぞれは、 "echo"コマンドレットへのパイプラインと同じように動作します。スクリプトとして

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 
} 

機能として

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(ValueFromPipeline=$true)] 
     $piped 
    ) 

    # do something with $piped 
} 

唯一の1つのパラメータはパイプライン入力に直接結合できることは明らかでなければなりません。ただし、複数のパラメータをパイプライン入力の異なるプロパティにバインドすることができます。

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

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

    # do something with $prop1 and $prop2 
} 

これは、別のシェルを学習するのに役立ちます。

関連する問題