Pipeline call function

Welcome Forums General PowerShell Q&A Pipeline call function

This topic contains 3 replies, has 2 voices, and was last updated by

 
Member
3 years, 6 months ago.

  • Author
    Posts
  • #25512

    Participant
    Points: 0
    Rank: Member

    Hi developer,

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

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

    aa.ps1
    Import-Module "c:\....Function.ps1"
    Get-Content .\test1.txt | CommaSeparated | .......

    bb.ps1
    Import-Module "c:\....Function.ps1"
    Get-Content .\test2.txt | CommaSeparated | .......

  • #25513

    Member
    Points: 0
    Rank: Member

    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

      Participant
      Points: 0
      Rank: Member

      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

    Member
    Points: 0
    Rank: Member

    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.

The topic ‘Pipeline call function’ is closed to new replies.