I'm currently building a module for Directory Opus, which is an alternative file browser for Windows Explorer, and I'm running into a bit of a challenge. I want to use a single parameter in my function that can work as both a standard string and a switch. Essentially, I have a function called `invoke-foo`, and I need it to recognize calls like these:
1. `invoke-foo -myParam NewWindow` (this should be a standard string)
2. `invoke-foo -myParam NewTab` (again, a standard string)
3. `invoke-foo -myParam` (should act like a switch if no value is supplied)
However, currently, trying to run `invoke-foo -myParam` without a value raises an error. I've explored some options in the PowerShell documentation regarding function parameters but haven't found a way to allow this kind of functionality. Got any ideas?
3 Answers
Just remember, passing `invoke-foo -myParam` isn't the same as passing an empty string. If you wanted to test with an empty string, you would do `invoke-foo -myParam ""`. That might change how your function interprets the input.
You could try this workaround:
```powershell
function Invoke-Foo {
param(
[switch]$myParam,
[Parameter(ValueFromRemainingArguments)] $otherParam
)
if ($myParam -and $otherParam -eq 'foo') { 'foo' }
elseif($myParam -and $otherParam -eq 'bar') { 'bar' }
elseif($myParam) { $true }
}
invoke-foo -myParam 'bar'
invoke-foo -myParam
```
Just a thought, though it's a bit lighthearted!
For real, though, maybe there's a funky way to tap into `$MyInvocation` and analyze the command call!
Have you considered using parameter sets? This might let you define the same parameter name across different contexts! Check out the [PowerShell docs on parameter sets](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parameter_sets?view=powershell-7.5) for more.
I haven't tried that with the same parameter name yet but it's definitely worth experimenting! I might give it a shot when I'm back at my computer.
That sounds like a solid approach. Let me know how it goes!
True, but you need a way to make the parameter optional without causing errors, right?