Quick PowerShell note: Get available constructors

When you’re working with PowerShell, you occasionally will be using .Net types to create objects . One thing that I noticed is that it’s quite difficult to know the correct types of the arguments that you can pass to the different constructor methods. Some piece of PowerShell that I had was:

$transformPath = "$PWD\Microsoft.Web.XmlTransform.dll”
[System.Reflection.Assembly]::LoadFile($transformPath)

In that (small) example, I did a reflection of the XDT DLL, and I wanted to create an “XmlTransformation” object to do some XDT transformations (which is pretty cool, and recently release to NuGet btw!). In that case, I wanted to know what the available constructors are, and what arguments you can pass. If you do this with for example C#, you can just press F12, and that’s it. But not with PowerShell. After some google’ing bing’ing I found this little function:

function get-Constructor ([type]$type, [Switch]$FullName)
{
    foreach ($c in $type.GetConstructors())
    {
        $type.Name + "("
        foreach ($p in $c.GetParameters())
        {
             if ($fullName)
             {
                  "`t{0} {1}," -f $p.ParameterType.FullName, $p.Name 
             }else
             {
                  "`t{0} {1}," -f $p.ParameterType.Name, $p.Name 
             }
        }
        ")"
    }
}

All you have to do now is run this:

get-Constructor Microsoft.Web.XmlTransform.XmlTransformation

XmlTransformation(
	String transformFile,
)
XmlTransformation(
	String transform,
	IXmlTransformationLogger logger,
)
XmlTransformation(
	String transform,
	Boolean isTransformAFile,
	IXmlTransformationLogger logger,
)
XmlTransformation(
	Stream transformStream,
	IXmlTransformationLogger logger,
)

That’s pretty cool, that was exactly what I was looking for! Now I can create an object using:

$xmlTransformation = new-object Microsoft.Web.XmlTransform.XmlTransformation –ArgumentList $env.OuterXml, $false, $null

Small, but useful. 

Written by
Alexander Vanwynsberghe
Join the discussion

Menu

Alexander Vanwynsberghe

Belgium-based entrepreneur. Into technology, innovation and a bit of cycling and running too. Evangelist for everything related to smart-tech.