I'm trying to handle the most obvious case of functions using mixed optional inputs. I would like the function to be able to process correctly the following command line options:
usage:
yolo 'BB' 'CC'
'AA' | yolo 'CC'
As you might imagine, 'BB' could be an input filepath, and 'CC' a RegEx...
I have tried a lot, and can do either with pipe or without pipe (using args[]
), but not both.
function yolo {
param(
[Parameter(Mandatory = $false, Position=0, ValueFromPipeline = $true)] [string] $AA,
[Parameter(Mandatory = $false, Position=1)] [string] $BB,
[Parameter(Mandatory = $false, Position=2)] [string] $CC
)
$n=$($args.count); $p=$($PsBoundParameters.Count)
Write-Host "N: $n`nP: $p`n"
Write-Host "`nAA: $AA`nBB: $BB`nCC: $CC`n"
$PSBoundParameters.Keys
}
However, all the variables get jumbled up...
# Example-1
# yolo
N: 0
P: 0
AA:
BB:
CC:
# Example-2
# yolo "AA" "BB"
N: 0
P: 2
AA: AA
BB: BB
CC:
AA
BB
# Example-3
# "AA" | yolo "BB"
yolo: 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.
N: 0
P: 1
AA: BB
BB:
CC:
AA
Q: How can I ensure they end up in the right variable, regardless if passed from pipe or as arguments?
(a) Why doesn't the piped string end up in any of the parametered variable?
(b) How do I access it?
PS. Similarly named questions, where not of any help.
Your function is working as designed.
But you can't bind a value in two ways at the same time.
'AA' | yolo
is the same thing as
yolo 'AA'
and yolo -AA 'AA'
You can't for obvious reason use parameter bindings properly for the same parameter in more then one way at the same time.
So 'AA' | yolo 'AA'
and 'AA' | yolo -AA 'AA'
will not work.
yolo 'AA' -AA 'AA'
will also mess things up.
'AA' | yolo -BB 'BB'
is however ok.
You just cant use the pipeline
if also using Position 0
or param -AA
at the same time...
Anything else goes.