Can I Use a Parameter as Both a Switch and a Standard String in PowerShell?

0
4
Asked By CreativeSparrow42 On

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

Answered By SmartScripter42 On

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.

FunctionFan001 -

True, but you need a way to make the parameter optional without causing errors, right?

Answered By CheekyDev007 On

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!

SillyScriptMaster -

For real, though, maybe there's a funky way to tap into `$MyInvocation` and analyze the command call!

Answered By CuriousCoder001 On

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.

TechExplorer99 -

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.

PowerGuru68 -

That sounds like a solid approach. Let me know how it goes!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.