2012-08-09 9 views
6

RISOLTO:Come si scrive una funzione di PowerShell che legge dall'ingresso con pipe?

Di seguito sono riportati gli esempi più semplici di funzioni/script che utilizzano l'input con pipe. Ognuno si comporta come piping per il cmdlet "echo".

come funzioni:

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 
    } 
} 

come script:

# Echo-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 
    } 
# Echo-Pipe2.ps1
foreach ($i in $input) { 
    $i 
} 

Ad es

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 

risposta

12

si ha anche la possibilità di utilizzare funzioni avanzate, invece che l'approccio di base di cui sopra:

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

    # do something with $piped 
} 

dovrebbe essere ovvio che un solo parametro può essere associato direttamente a input da pipeline. Tuttavia, è possibile avere più parametri legano a diverse proprietà su input della pipeline:

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

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

    # do something with $prop1 and $prop2 
} 

Spero che questo ti aiuta il vostro viaggio per imparare un'altra shell.

Problemi correlati