I have the following PowerShell function that works as intended for pipeline and parameter usage:
function ext {
process {
[System.IO.Path]::ChangeExtension($_ ? $_ : $args[0], $_ ? $args[0] : $args[1])
}
}
Is it possible to simplify/minify this function by maybe using some Automatic Variables I don't know about, but without lengthening the code.
I explicitly don't want to go through all the parameter syntax like [Parameter(ValueFromPipeline=$True)]
and defining each parameter explicitly since it would double the length of the function, which is exactly not my goal, unlike in these posts:
The only possible simplifications to your current code are using a filter
instead of a function
with a process
and removing System
from System.IO.Path
. There is no automatic variable that covers pipeline and positional binding both in 1.
filter ext { [IO.Path]::ChangeExtension($_ ? $_ : $args[0], $_ ? $args[0] : $args[1]) }
If you want to give your code more meaning or context you could use .ExpectingInput
in your conditions however this makes it longer:
filter ext {
[IO.Path]::ChangeExtension(
$MyInvocation.ExpectingInput ? $_ : $args[0],
$MyInvocation.ExpectingInput ? $args[0] : $args[1])
}