2012-08-09 17 views
6

सोल्वेड:पाइप किए गए इनपुट से पढ़ने वाले पावरहेल फ़ंक्शन को आप कैसे लिखते हैं?

निम्नलिखित पाइप इनपुट का उपयोग करने वाले कार्यों/स्क्रिप्ट के सबसे सरल संभव उदाहरण हैं। प्रत्येक "गूंज" 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 
} 

आशा इस अपनी यात्रा एक अन्य सुरक्षा जानने के लिए आगे आप में मदद करता है।

 संबंधित मुद्दे

  • कोई संबंधित समस्या नहीं^_^