My Technical Notes

Thursday, 19 February 2015

PowerShell: Instantiating Objects and Finding Constructor Parameters

Instantiating an object has a similar syntax to C#:


PS H:\> New-Object System.DateTime @(2012, 3, 12)
12 March 2012 00:00:00

However, this is a bit deceptive. Explicitly specifying the parameter names reveals how it works:


PS H:\> New-Object -TypeName System.DateTime -ArgumentList @(2012, 3, 12)
12 March 2012 00:00:00

The `TypeName` parameter is actually a `string`. However, we still get completion on it, so we don't have to remember all the type names (except the containing namespace). The `ArgumentList` parameter is just an object array (`Object[]`). PowerShell ISE provides no information on the constructor parameters.

As a means of listing the constructor parameters, the PowerShell team have written a function Get-Constructor which lists all of the constructors for a given type:


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

No comments: