Home > Software engineering >  Correct param type for piping from Get-Content (PowerShell)?
Correct param type for piping from Get-Content (PowerShell)?

Time:10-28

What is the correct type for piping all of the content from Get-Content?

My script:

param(
    [Parameter(ValueFromPipeline)]
    [???]$content
)

Write-Output $content

According to the docs for PowerShell 5.1, Get-Content returns "a collection of objects", but I'm not sure how to specify that in PowerShell. Without specifying a type for the [???], only the last line of the file is output.

CodePudding user response:

Regarding your last comment:

When I specify [string] or [string[]], it is still only printing out the last line of the file. Is this related to missing the process block?

This is correct, otherwise your function, scriptblock or script is executed in the end block, if you want them to be able to process input from pipeline, you must add your logic in the process block.

Note, this assumes you want to use ValueFromPipeline which, in effect, converts it into an advanced function.

If you want it be able to process input from pipeline but also be compatible with positional binding and named parameter you would use [string[]] and a loop:

param(
    [Parameter(ValueFromPipeline)]
    [string[]] $Content
)

process {
    foreach($line in $Content) {
        $line
    }
}

Then, assuming the above is called myScript.ps1, you would be able to:

Get-Content .\test.txt | .\myScript.ps1

And also:

.\myScript.ps1 (Get-Content .\test.txt)
  • Related