powershell - how to write a (unix like) function that accepts pipe or file name input? -
e.g. want head
either accepts array piped , select-object -first
, or, receives list of file names parameters , outputs first lines of each. cat $filename | head
should work head $filename
here's i've tried 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 causes function ignore 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 : input object cannot bound parameters command either because command not take pipeline input or input , properties not match of parameters take pipeline input. @ line:1 char:6 + $a | head 1 + ~~~~~~ + categoryinfo : invalidargument: (1:int32) [head], parameterbindingexception + fullyqualifiederrorid : inputobjectnotbound,head
you can achieve using parameter sets:
function head { [cmdletbinding()] param( [parameter( parametersetname = 'content', valuefrompipeline = $true, mandatory = $true )] [string[]] $content , [parameter( parametersetname = 'file', valuefromremainingarguments = $true , mandatory = $true )] [string[]] $path, [parameter()] [uint64] $count = 5 ) begin { write-verbose "parameter set name: $($pscmdlet.parametersetname)" } process { write-verbose "content: $content" write-verbose "path: $path" write-verbose "count: $count" } }
first, take @ output of running get-help head
:
name head syntax head -content <string[]> [-count <uint64>] [<commonparameters>] head -path <string[]> [-count <uint64>] [<commonparameters>]
you can see interprets 2 different sets, , each parameter mandatory in own set.
you can call -verbose
see demonstration of how working:
# content pipeline 'one','two','three' | head -verbose # files array head -verbose 'file1','file2','file3' # files remaining arguments head -verbose 'file1' 'file2' 'file3'
Comments
Post a Comment