0

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

Duncan_McCloud
  • 543
  • 9
  • 24

1 Answers1

2

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
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • Sorry I have forgot to add that i would like to call the script like this: Script.ps1 System.IO.StreamWriter. In my $class variable I will have a strign which represent the full name of the class Type. – Duncan_McCloud Apr 18 '14 at 13:32
  • 1
    Should work for that. I updated the script with example usage. – mjolinor Apr 18 '14 at 13:42
  • Yes It Works, thanks!. Here another method I have just found: [System.Type]::GetType($class).GetConstructors() | ... – Duncan_McCloud Apr 18 '14 at 13:45
  • You could probably also replace `[string]$class` with `[type]$class`. – x0n Apr 21 '14 at 00:41