PowerTip: Find Class Constructors in PowerShell 5


Summary: Learn how to easily find class constructors.

Hey, Scripting Guy! Question How can I use Windows PowerShell 5.0 to find the constructor overloads for a new class I want to create?

Hey, Scripting Guy! Answer Place the class in square brackets, and call the static New method with no parentheses, for example:

[datetime]::new

Comments (5)

  1. ITGuy says:

    Does the Class remain in the Creating PowerShell Session, or is it persistent and available to additional Sessions?

  2. Mihai says:

    How can I see that in Powershell v4 ?

  3. Boe Prox says:

    @Mihai
    Check out my Get-Constructor function here to view the available constructors:
    https://gallery.technet.microsoft.com/scriptcenter/Get-Constructor-a8911ebe

  4. gaelcolas says:

    I was playing with that yesterday actually!
    In case other people are looking at how to get extended information about the constructors, the following will give you the details:
    $ctors = [datetime].GetConstructors()
    $ctors
    Then if you want parameter details for a constructor, you could do something like:
    $ctors[2].GetParameters()
    Based on that I created two functions that allows to easily create a wrapper to instantiate a class without too much code for most (but not all) cases. Beware, this is still a draft that needs test, refactoring, help and comments!
    https://gist.github.com/gaelcolas/704e33fedbcd548c9e42#file-dynamicparam-draft-ps1

  5. gaelcolas says:

    Oh yeah Boe Prox’s code much nicer than mine, I should re-use it actually 🙂

Skip to main content