Process Data (Part 3)

by Feb 4, 2016

In parts 1 and 2, you learned how a PowerShell function can process information that was submitted to parameters or piped via the pipeline. In our third part, we'd like to show how a function can receive text lines and produces one string from it.

Here is a function that accepts text lines both via parameter and pipeline. The function uses a StringBuilder object to collect all incoming text lines, and then produces one string from all lines received:

#requires -Version 2
function Collect-Text
{
  param
  (
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [String[]]
    [AllowEmptyString()] 
    $Text
  )

  begin
  {
    $sb = New-Object System.Text.StringBuilder
  }

  process
  {
   foreach ($line in $Text)
   {
     $null = $sb.AppendLine($line)
   }
  }
  end
  {
    $result = $sb.ToString()
    $result
  }
}

Note how you can submit text lines either via parameter or via pipeline:

  
PS C:\> Collect-Text -Text 'Line 1', '', 'Line 2'
Line 1

Line 2


PS C:\> 'Line 1', '', 'Line 2' | Collect-Text 
Line 1

Line 2 
 

Take a look at the parameter: it uses the attribute [AllowEmptyString()]. This makes sure the parameter can also accept empty strings. Empty strings are not allowed for mandatory parameters without this attribute.

 

Throughout this month, we'd like to point you to three awesome community-driven global PowerShell events taking place this year:

Europe: April 20-22: 3-day PowerShell Conference EU in Hannover, Germany, with more than 30+ speakers including Jeffrey Snover and Bruce Payette, and 60+ sessions: www.psconf.eu.

Asia: October 21-22: 2-day PowerShell Conference Asia in Singapore. Watch latest announcements at www.psconf.asia

North America: April 4-6: 3-day PowerShell and DevOps Global Summit in Bellevue, WA, USA with 20+ speakers including many PowerShell Team members: https://eventloom.com/event/home/PSNA16

All events have limited seats available so you may want to register early.

Twitter This Tip! ReTweet this Tip!