引用System.DirectoryServices.ResultPropertyCollection

时间:2020-03-05 18:40:11  来源:igfitidea点击:

我在这里错过了一些东西:

$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

解决方案

回答

我相信这与PS在""中插入信息的方式有关。试试这个:

"用$($ _。properties).name引起的服务器名称"

或者,我们甚至可能需要另外一组$()。我现在无法在某个地方进行测试。

回答

关闭-以下内容可以正常运行,但是如果有人有更深入的解释,我将很感兴趣。

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

因此,似乎$ _。properties.name并不符合我的预期。如果我正确地可视化,则name属性是多值的事实会导致它返回一个数组。我(哪个)可以解释以下原因的工作原理:

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

如果"名称"是一个字符串,则应返回第一个字符,但是由于它是一个数组,因此将返回第一个字符串。

回答

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

在这种情况下,ToString方法将返回类型名称。我们可以强制对变量和成员的求值,类似于EBGreen建议的那样,但是可以使用

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

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

我们将返回一组属性是正确的。如果将$ computer [0] .properties通过管道传递给get-member,则可以直接从命令行浏览对象模型。

重要的部分如下。

TypeName: System.DirectoryServices.ResultPropertyCollection
  
  Name                    MemberType            Definition
  
  
  
  Values            Property              System.Collections.ICollection Values {get;}