2008-08-17 102 views
1

我在这里失去了一些东西:报价System.DirectoryServices.ResultPropertyCollection

$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 

回答

1

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

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

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

在其他情况下的PowerShell正在评估的变量和成员指定的第一,然后将它添加到以前的字符串。

你是对的,你正在找回一组属性。如果您将$ computer [0] .properties设置为get-member,则可以从命令行直接浏览对象模型。

重要的部分如下。

类型名:System.DirectoryServices.ResultPropertyCollection

名称MemberType定义


值属性System.Collections.ICollection值{获得;}

0

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

“的报价$服务器名称($ _属性)。名称”

或者你甚至可能需要一个多集的$()。我现在不是我可以测试的地方。

0

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

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

因此,似乎$ _。properties.name不会像我预期的那样顺从。如果我正确可视化,名称属性是多值的事实导致它返回一个数组。这(我认为)应该能解释了以下工作:

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

如果“名”是一个字符串,应返回的第一个字符,而是因为它是一个数组,它返回的第一个字符串。