引用System.DirectoryServices.ResultPropertyCollection

时间:2008-08-17 17:33:55

标签: .net powershell scripting active-directory

我在这里遗漏了一些东西:

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher  
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry  
$objSearcher.Filter = ("(objectclass=computer)")  
$computers = $objSearcher.findall()  

所以问题是为什么以下两个输出不同?

$computers | %{ 
"Server name in quotes $_.properties.name" 
"Server name not in quotes " + $_.properties.name 
}
PS> $computers[0] | %{"$_.properties.name"; $_.properties.name}
System.DirectoryServices.SearchResult.properties.name
GORILLA

3 个答案:

答案 0 :(得分:1)

当你在字符串中包含$ _。properties.name时,它返回了属性的类型名称。当变量包含在字符串中并且对字符串求值时,它会调用该变量引用的该对象上的ToString方法(不包括之后指定的成员)。

在这种情况下,ToString方法返回类型名称。你可以强制评估变量和成员,类似于EBGreen所建议的,但是使用

"Server name in quotes $($_.properties.name)"  

在另一种情况下, PowerShell 首先评估变量和成员,然后将其添加到上一个字符串。

你回来了一系列属性是对的。如果将 $ computer [0] .properties 传递给get-member,则可以直接从命令行浏览对象模型。

重要的部分如下。

  

TypeName:System.DirectoryServices.ResultPropertyCollection

     

名称成员类型定义

     
     

值属性System.Collections.ICollection值{get;}

答案 1 :(得分:0)

我认为这与PS在“”中插入信息的方式有关。试试这个:

“服务器名称用引号$($ _。properties).name”

或者你甚至可能还需要一组$()。我现在不能在某个地方测试它。

答案 2 :(得分:0)

关闭 - 以下工作正常,但如果有人有更深入的解释,我会感兴趣。

PS C:\> $computers[0] | %{ "$_.properties.name"; "$($_.properties.name)" }
System.DirectoryServices.SearchResult.properties.name
GORILLA

所以看起来$ _。properties.name并不像我预期的那样顺从。如果我正确可视化,name属性为多值的事实会导致它返回一个数组。其中(我认为)可以解释为什么以下有效:

$computers[0] | %{ $_.properties.name[0]}

如果“name”是一个字符串,则应返回第一个字符,但因为它是一个数组,所以它返回第一个字符串。