Pipeline call function

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 2 months ago.

  • Author
    Posts
  • #25512
    Profile photo of PowerShell84
    PowerShell84
    Participant

    Hi developer,

    How to pipeline call a method or function if possible? e.g

    [i][b]Function.ps1[/b][/i]
    function CommaSeparated
    {
    ForEach-Object {($_ -replace "\s+",",")}
    }

    [i][b]aa.ps1[/b][/i]
    Import-Module "c:\....Function.ps1"
    Get-Content .\test1.txt | CommaSeparated | .......

    [i][b]bb.ps1[/b][/i]
    Import-Module "c:\....Function.ps1"
    Get-Content .\test2.txt | CommaSeparated | .......

  • #25513
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    You'd need to set up your function to accept pipeline input, and use a process block. However, in this case, it may be even faster to just use a filter (which is like a function that only has a process block, and also happens to execute quite a bit faster):

    filter CommaSeparated
    {
        $_ -replace "\s+",","
    }
    
    • #25518
      Profile photo of PowerShell84
      PowerShell84
      Participant

      thank you for replying back to me

      I need tutorial about only function to input it and process block
      Do you have any link or reference?

  • #25521
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That information is mainly in the about_Functions and about_Functions_Advanced_Parameters help files. In its simplest form, that would look like this:

    function CommaSeparated
    {
        process
        {
            $_ -replace "\s+",","
        }
    }
    

    A more advanced approach (allowing for different ways of calling the function) would be something like this:

    function CommaSeparated
    {
        [CmdletBinding()]
        param (
            [Parameter(ValueFromPipeline = $true)]
            [string[]] $String
        )
    
        process
        {
            foreach ($s in $String)
            {
                $s -replace "\s+",","
            }
        }
    }
    

    This approach of accepting both pipeline input, as well as an array passed via the command line (eg, CommaSeparated -String 'one two', 'three four', 'five six') is a common user-friendly experience for functions that you plan to share with others.

You must be logged in to reply to this topic.