E.g. I want something like head
that either accepts an array piped to it and then does select-object -first
, or, receives a list of file names as parameters and outputs the first lines of each. So cat $filename | head
should work like head $filename
Here's what I've tried so far:
Function head( )
{
param (
[switch] $help = $false,
[parameter(mandatory=$false,ValueFromPipeline=$true)] [object[]] $inputs,
[parameter(ValueFromRemainingArguments=$true)] [String[]] $files
)
If( $help )
{
Write-Host "usage: $($MyInvocation.MYCommand) [<file>] <numLines>"
return
}
$lines = 0
if ($files -and [int]::TryParse($files[0], [ref]$lines)) {
$null,$files = $files
} else {
$lines = 10
}
$input | select-object -First $lines
if ($files) {get-content -TotalCount $lines $files}
}
But this causes the function to ignore the first parameter:
C:\Users\idror.TLV-WPVAJ> head C:\temp\now.ps1
C:\Users\idror.TLV-WPVAJ> head C:\temp\now.ps1 C:\temp\now.ps1
Function head( )
{
param (
[switch] $help = $false,
[parameter(mandatory=$false,ValueFromPipeline=$true)] [object[]] $input,
[parameter(ValueFromRemainingArguments=$true)] [String[]] $files
)
If( $help )
{
C:\Users\idror.TLV-WPVAJ> $a | head
1
2
3
C:\Users\idror.TLV-WPVAJ> $a | head 1
head : The input object cannot be bound to any parameters for the command either because the command does not take
pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:6
+ $a | head 1
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (1:Int32) [head], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,head