2012-08-09 118 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 
} 

例如

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 
} 

應該是顯而易見的,只有一個參數,可以直接綁定到管道輸入。但是,你可以有多個參數綁定到不同性質的管道輸入:

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

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

    # do something with $prop1 and $prop2 
} 

希望這可以幫助你在你的旅程,學習另一種外殼。