0

I've written a bunch of classes that reach out to an API and get JSON. When compiled, I get nice commands like get-host, get-version, get-app, etc.

each cmdlet takes an argument like -host or -app.

I've got about 160 of these that I can write but I'm now looking to write a more generic cmdlet that can accept arbitrary parameters and values.

From what I can see, I can't declare parameters as such where i can issue

get-info -app "appname"

or

get-info -host "hostname"

or

get-info -version "5.5"

unless i declare all the parameters of which there could be hundreds. Also, if the parameter is not declared, it throws a nice error

Get-Info : A parameter cannot be found that matches parameter name 'host'.

Is there a way I can not declare any parameters and then parse the arguments manually or is there a something in c# to automatically parse the list of arguments and then assign them to variables named appropriately?

for example

get-info -host "hostname" -backup "backupid"

and the variables host and backup would be set automatically?

anoopb
  • 533
  • 4
  • 6
  • 20

1 Answers1

1

Accept your arbitrary parameters as a HashTable:

get-mydata @{ Host = "hostname"; version = "1.0" }

That is how most of the built-in cmdlets handle arbitrary KVPs.

Mitch
  • 21,223
  • 6
  • 63
  • 86
  • That's a great idea. I'll give that a shot. I wish i didn't need to do it as a hashtable but I think it's a great option for a "catch all" cmdlet. – anoopb Oct 23 '14 at 16:35
  • Thanks! that worked beautifully. I actually have a function that reads in parameters like normal and then the function creates a hashtable out of it and calls the generic cmdlet. thanks again. – anoopb Oct 30 '14 at 15:55