Following the examples in https://stackoverflow.com/a/48877892/2954547 and https://stackoverflow.com/a/31458007/2954547, I wrote this function:
function Run-Program {
param(
[Parameter(Position = 0, Mandatory = $true)] [String]$Executable,
[Parameter(Position = 1, ValueFromRemainingArguments)] [String[]]$ProgramArgs
)
if ($MyInvocation.ExpectingInput){
$input | & $Executable @ProgramArgs
} else {
& $Executable @ProgramArgs
}
}
I tried testing it:
'abcdef' | Run-Program python -c 'import sys; print(sys.stdin.read())'
But I got this error:
Run-Program: 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.
Whereas I expected the string 'abcdef'
to be passed to stdin of python
, as per the automatic variable $input
.
I was able to get this to work by explicitly declaring $input
as a parameter:
param(
[Parameter(ValueFromPipeline)] $input,
[Parameter(Position = 0, Mandatory = $true)] [String]$Executable,
[Parameter(Position = 1, ValueFromRemainingArguments)] [String[]]$ProgramArgs
)
but that seems to defeat the purpose of having an automatic variable.
Did I misunderstand something in the usage of $input
? Do I need to do something different to ensure that the type of the pipeline input is appropriate for the automatic variable $input
?