0

不幸的是,Powershell ISE 无法为 .NET 类构造函数显示智能感知。我找到了一个可以获取构造函数列表的脚本:

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

它完美地工作

有没有办法使用变量而不是固定的类名?有人这样想:

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

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

我将以这种方式调用脚本:

Script.ps1 System.IO.StreamWriter

现在它返回以下错误:

在 D:\LAB\POWERSHELL\CMD-LETS\GetConstructor.ps1:6 char:2 + [$class].GetConstructors() | + ~ '[' 后缺少类型名称。在 D:\LAB\POWERSHELL\CMD-LETS\GetConstructor.ps1:6 char:26 + [$class].GetConstructors() | + ~ 在 '(' 之后应该有一个表达式。+ CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : MissingTypename

4

1 回答 1

2

您需要从 $Class 字符串参数创建一个 Type 对象:

$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
于 2014-04-18T13:20:26.333 回答