【问题标题】:Using non-standard parameter data types in Powershell advanced functions在 Powershell 高级函数中使用非标准参数数据类型
【发布时间】:2011-02-22 21:08:01
【问题描述】:

我注意到大多数 Powershell 高级函数声明映射到特定 .Net 类型的标准数据类型(字符串、int、bool、xml、数组、哈希表等)的参数。

如何使用另一种 .Net 数据类型声明高级函数参数?例如,这是一个人为的例子:

function Do-Something
{
    [CmdletBinding()]
    Param(        
        [System.Xml.XPathNodeList] $nodeList
    )

    Begin {}
    Process 
    {    
        Foreach ($node in $nodeList)
        {
            Write-Host $node
        }        
    }
    End {}
}        

# Prepare to call the function:
$xml = [xml](get-content .\employee.xml)
$nodeList = $xml.SelectNodes("//age")

# Call the function passing an XPathNodeList:
do-something $nodeList

调用此函数会导致以下运行时错误:

Unable to find type [System.Xml.XPathNodeList]: make sure that the assembly
containing this type is loaded.

这可以用 LoadWithPartialName() 来完成吗?如何?

假设这是可能的,这里有一个辅助问题:以这种方式使用非标准类型会违反“最佳实践”吗?

【问题讨论】:

    标签: function powershell types parameters


    【解决方案1】:

    只要您使用 cmdlet Add-Type 之类的东西来加载定义自定义类型的程序集,就可以使用自定义 .NET 类型。但是在这种情况下,程序集System.Xml 已经加载。出现问题是因为您指定的类型是私有类型,即仅在 System.Xml 程序集中可见。

    PS> $nodeList.GetType()
    
    IsPublic IsSerial Name                     BaseType
    -------- -------- ----                     --------
    False    False    XPathNodeList            System.Xml.XmlNodeList
    

    改用它的公共基类:

    [CmdletBinding()]
    Param(
        [Parameter()]        
        [System.Xml.XmlNodeList] 
        $nodeList
    )
    

    【讨论】:

      【解决方案2】:

      使用标准 .NET 对象作为函数参数应该没有任何问题 - 您遇到的错误与卸载的程序集相关,这就是我要查看的地方。检查您的个人资料,确保没有发生任何异常情况 - 详情请参阅 http://msdn.microsoft.com/en-us/library/bb613488%28v=vs.85%29.aspx

      如果真的到了,可以使用下面的方式来加载System.Xml(强制转换为Void来抑制加载的文本输出):

      [Void][System.Reflection.Assembly]::LoadWithPartialName("System.Xml")
      

      【讨论】:

      • 哎呀 - 错过了上面的 CmdletBinding,Keith 是完美的。
      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多