Receiving Input via Pipeline

by Sep 1, 2016

In the previous tip we illustrated how Convert-Umlaut was able to convert special characters in a string. This becomes even more useful if a function accepts pipeline input. Let’s check out the changes required to add that.

Without pipeline support, the function looks like this:

#requires -Version 3


function Convert-Umlaut
{
  param
  (
    [Parameter(Mandatory)]
    $Text
  )
    
  $output = $Text.Replace('ö','oe').Replace('ä','ae').Replace('ü','ue').Replace('ß','ss').Replace('Ö','Oe').Replace('Ü','Ue').Replace('Ä','Ae')
  $isCapitalLetter = $Text -ceq $Text.toUpper()
  if ($isCapitalLetter) 
  { 
    $output = $output.toUpper() 
  }
  $output
}

It can be run like this:

 
PS C:\> Convert-Umlaut -Text "Mößler, Christiansön" 
Moessler, Christiansoen
 

However, it cannot be run like this:

 
PS C:\> "Mößler, Christiansön" | Convert-Umlaut
 

To add pipeline support, two things are needed: (a) the parameter needs to be marked that should accept pipeline data, and (b) the code that needs to be iterated for each incoming element must be placed into a “process” block. Here are the changes:

#requires -Version 3


function Convert-Umlaut
{
  param
  (
    [Parameter(Mandatory, ValueFromPipeline)]
    $Text
  )
    
  process
  {
    $output = $Text.Replace('ö','oe').Replace('ä','ae').Replace('ü','ue').Replace('ß','ss').Replace('Ö','Oe').Replace('Ü','Ue').Replace('Ä','Ae')
    $isCapitalLetter = $Text -ceq $Text.toUpper()
    if ($isCapitalLetter) 
    { 
      $output = $output.toUpper() 
    }
    $output
  }
}

Now, the pipeline steaming works, too:

 
PS C:\> "Mößler, Christiansön" | Convert-Umlaut 
Moessler, Christiansoen
 

Twitter This Tip! ReTweet this Tip!