Author Posts

October 1, 2015 at 10:19 am

I'm playing around with the latest WMF 5 build doing fun stuff with classes, and I ran across a situation where I'd like to use optional parameters instead of creating a bunch of overloads. I can't find much about this topic either online or in the about_classes help file. Also I'm not a real developer so I could be thinking about this all wrong. This C# reference mentions the use of optional arguments to a method, which I think is what I'd like to do with powershell:

Basically I have a class IB_DNSARecord with a method Get:


This will get the DNS A record that matches that name exactly. Another option would be to do a search that matches any record that is similar rather than exact, and ideally I'd like to do it like this:


where the third parameter determines whether or not to do a strict search (True would be the default if not specified). Currently this blows up on me, so it seems like I'd have to do an overload for it and re-use a bunch of code.

Any ideas?

October 1, 2015 at 10:33 am

Not yet, but I believe that's on their list of things to add (and the parser already supports the syntax for assigning values to parameters, which is a bit confusing at this point since the rest of the functionality isn't implemented yet.)

October 1, 2015 at 10:39 am

That explains it, thanks. So if default parameter values don't actually work yet that explains the error I get when trying the overload route. thanks!

Should I go put feedback on connect or something or is that already in their to do list?

October 1, 2015 at 10:49 am

Pretty sure it's already on their to-do list. However, in the meantime, you can always fall back on the old .NET 2.0 way of accomplishing this without too much duplicate code:

class IB_DNSARecord
    static [IB_DNSARecord] Get([object] $GridMaster, [pscredential] $Credential, [bool] $Strict)
        # do stuff

    static [IB_DNSARecord] Get([object] $GridMaster, [pscredential] $Credential)
        return [IB_DNSARecord]::Get($GridMaster, $Credential, $false)

October 1, 2015 at 11:50 am

That works great, thanks!

I also learned if you leave out a parameter you can create a method calling loop and crash the ISE.....