2011-02-22 59 views
1

我注意到大多数Powershell高级函数都声明了映射到特定.Net的标准数据类型(string,int,bool,xml,array,hashtable等)的参数类型。在Powershell高级功能中使用非标准参数数据类型

如何使用另一个.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实现的呢?怎么样?

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

回答

2

只要您使用类似于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 
) 
0

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

如果真的涉及到它,你可以使用以下加载的System.Xml(铸造空隙抑制装载的文本输出):

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

哎呦 - 错过了上面列出CmdletBinding,Keith的是完美的。 – 2011-02-22 21:32:19