Piping data to functions

In addition to passing data to functions via parameters, functions can receive data directly from another object or command via a pipe "|". Receiving values by piping helps improve scripting by limiting the use of temporary variables, as well as more easily passing complex object types or descriptors.

How to do it...

In this recipe, we will create a simple function that receives input from command line as well as pipe. To do this, carry out the following steps:

  1. Create a simple function that accepts a parameter:
    Function Square-Num
    {
        Param([float] $FirstNum)
        Write-Host ($FirstNum * $FirstNum)
    }
  2. Use the ValueFromPipeline parameter to enable the script to accept input from the pipeline:
    Function Square-Num { Param([float] [Parameter(ValueFromPipeline ...

Get Windows Server 2012 Automation with PowerShell Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.