Can I Use a Parameter as Both a Switch and a Standard String in PowerShell?
Asked by
NO FALSE STARTS
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?
Answers
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.
Reply to this answer
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!
night ferry crossing: For real, though, maybe there's a funky way to tap into `$MyInvocation` and analyze the command call!
Reply to this answer
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.
museum accession: True, but you need a way to make the parameter optional without causing errors, right?
Reply to this answer
Add your answer
Answers are reviewed before publication.
switchback__trail: 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.
linen size 24: That sounds like a solid approach. Let me know how it goes!