Author Posts

May 21, 2015 at 4:00 am

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

May 21, 2015 at 4:07 am

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+",","
}

May 21, 2015 at 4:27 am

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?

May 21, 2015 at 4:37 am

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.