Question

Unfortunately Powershell ISE can't show intellisense for .NET Classes Constructor. I have found a script which can get the list of Constructor:

[System.IO.StreamWriter].GetConstructors() |
 ForEach-Object {
    ($_.GetParameters() |
        ForEach-Object {
            ‘{0} {1}’ -f $_.Name, $_.ParameterType.FullName 
        }) -join ‘,’
 }

It works perfectly

Is there a way to use a variable instead of a fixed class name ? Somethink like that:

Param(
    [Parameter(Mandatory=$True)]
    [string]$class 
)

[$class].GetConstructors() |
 ForEach-Object {
    ($_.GetParameters() |
        ForEach-Object {
            ‘{0} {1}’ -f $_.Name, $_.ParameterType.FullName 
        }) -join ‘,’
 } 

I will call the Script in this way:

Script.ps1 System.IO.StreamWriter

Now it return the following error:

At D:\LAB\POWERSHELL\CMD-LETS\GetConstructor.ps1:6 char:2 + [$class].GetConstructors() | + ~ Missing type name after '['. At D:\LAB\POWERSHELL\CMD-LETS\GetConstructor.ps1:6 char:26 + [$class].GetConstructors() | + ~ An expression was expected after '('. + CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : MissingTypename

Was it helpful?

Solution

You'll need to create a Type object from the $Class string argument:

$script = {
Param(
    [Parameter(Mandatory=$True)]
    [string]$class
)

([Type]$Class).GetConstructors() |
 ForEach-Object {
    ($_.GetParameters() |
        ForEach-Object {
            ‘{0} {1}’ -f $_.Name, $_.ParameterType.FullName 
        }) -join ‘,’
 }
 }

 &$script 'system.io.streamwriter'

stream System.IO.Stream
stream System.IO.Stream,encoding System.Text.Encoding
stream System.IO.Stream,encoding System.Text.Encoding,bufferSize System.Int32
stream System.IO.Stream,encoding System.Text.Encoding,bufferSize System.Int32,leaveOpen System.Boolean
path System.String
path System.String,append System.Boolean
path System.String,append System.Boolean,encoding System.Text.Encoding
path System.String,append System.Boolean,encoding System.Text.Encoding,bufferSize System.Int32
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top