我遗漏了一些东西:
$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发布于 2008-08-17 22:10:03
当字符串中包含$_.properties.name时,它将返回属性的类型名称。当字符串中包含变量并计算该字符串时,它将对该变量引用的对象(不包括之后指定的成员)调用ToString方法。
在本例中,ToString方法返回类型名称。您可以强制计算变量和成员的值,类似于EBGreen所建议的,但使用
"Server name in quotes $($_.properties.name)" 在另一个场景中,PowerShell首先计算指定的变量和成员,然后将其添加到前一个字符串中。
您得到的是一个属性集合,这是对的。如果您通过管道将$computer.properties传递给get-member,则可以直接从命令行浏览对象模型。
重要的部分在下面。
System.DirectoryServices.ResultPropertyCollection:
TypeName
名称MemberType定义
Values属性System.Collections.ICollection值{get;}
发布于 2008-08-17 17:41:14
我相信这与PS在"“中插入信息的方式有关。试试这个:
“引号中的服务器名称$($_.properties).name”
或者,您甚至可能还需要一组$()。我现在不在可以测试的地方。
发布于 2008-08-17 19:37:45
Close--下面的代码工作正常,但如果有人有更深入的解释,我会很感兴趣。
PS C:\> $computers[0] | %{ "$_.properties.name"; "$($_.properties.name)" }
System.DirectoryServices.SearchResult.properties.name
GORILLA所以看起来$_.properties.name并没有像我期望的那样顺从。如果我的可视化是正确的,那么name属性是多值的这一事实会导致它返回一个数组。这(我认为)可以解释为什么下面的方法是有效的:
$computers[0] | %{ $_.properties.name[0]}如果"name“是一个字符串,它应该返回第一个字符,但是因为它是一个数组,所以它返回第一个字符串。
https://stackoverflow.com/questions/13753
复制相似问题