xpt
xpt

Reputation: 22984

PowerShell, How to provide a pipe variable?

This is a high level question as the details might not be precise, as I'm not in my office but home.

I have a function that accept variables through pipe:

get-csv | myfunc

The pipe source is the fields from a .csv file.

How to define a variables and pipe into myfunc()? Would HashTable be good?

$my_pipe_variables = @{ Color = ‘Red’; Doors = 4; Convertible = $false}
$my_pipe_variables | myfunc

would that be the correct syntax?

Update:

I finally get around to try it but it is not working for me, as my myfunc accesses pipe variables directly via $_. Here is the demo:

function showThem { echo Color: $_.Color }

> [pscustomobject]@{ Color = ‘Red’; Doors = 4; Convertible = $false} | showThem
Color:

How can I make it works for myfunc, which accesses pipe variables directly via $_?

Upvotes: 1

Views: 1921

Answers (1)

mklement0
mklement0

Reputation: 437090

Import-Csv (not Get-Csv), for reading CSV data from a file, and ConvertFrom-Csv, for reading CSV data from a string, output a collection of custom objects (type [pscustomobject]) whose properties reflect the CSV data's columns.

To construct such custom objects on demand in order to simulate Import-Csv / ConvertFrom-Csv input, use the
[pscustomobject] @{ <propertyName>=<value>; ... } syntax (PSv3+).

E.g., to simulate 2 rows of CSV data with columns Color, Doors, and Convertible:

[pscustomobject] @{ Color = 'Red'; Doors = 4; Convertible = $false },
[pscustomobject] @{ Color = 'Blue'; Doors = 5; Convertible = $false } |
  ...

Separately, in order to make a function process input from the pipeline object by object via automatic variable $_, it must have a process { ...} block - see help topic about_Functions.

# Define the function body with a process { ... } block, which
# PowerShell automatically calls for each input object from the pipeline,
# reflected in automatic variable $_
function showThem { process { "Color: " + $_.Color } }

[pscustomobject] @{ Color = 'Red'; Doors = 4; Convertible = $false },
[pscustomobject] @{ Color = 'Blue'; Doors = 5; Convertible = $false } |
  showThem

Note: In PowerShell, echo is an alias of Write-Output, whose explicit use is rarely needed; instead, the function relies on PowerShell's implicit output: the result of the string concatenation (+) implicitly becomes the function's output.

The above yields:

Color: Red
Color: Blue

Upvotes: 3

Related Questions