为什么Powershell& AD返回换行?

时间:2014-08-01 18:43:05

标签: powershell active-directory

我有这个Powershell代码:

$strFilter = "(&(objectCategory=User)(Description=*MD))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colProplist = "name", "department", "description"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties
         $objItem.name + "|" + $objItem.department + "|" + $objItem.description
    }

由于某些原因,它返回了新的行。我怎么能阻止这个?

输出如下:

Bob Dole
|
SOME DEPT
|
Bob description
Rick James
|
ANOTHER DEPT
|
Rick description

将最后一个块更改为:

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties
         $colResults.Properties|%{($_.name,$_.department,$_.description) -join "|"}
    }

没有给我任何东西,只是一堆:

||
||
||
||
||
||

我也尝试过:

$colResults.Properties|%{($_.name,$_.department,$_.description) -join "|"}

只有:

||

2 个答案:

答案 0 :(得分:1)

您必须意识到$objItem.attribute始终是一个集合。我怀疑这是你所看到的问题的根本原因。试试这个:

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties
         $objItem.name[0] + "|" + $objItem.department[0] + "|" + $objItem.description[0]
    }

问题是,如果这些属性中的任何一个为空,则可能会出现错误。要避免它(并获得相同的体验),您可以使用一元-join(使用-f来简化阅读):

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties
         '{0}|{1}|{2}' -f @(
            (-join $objItem.name)
            (-join $objItem.department) 
            (-join $objItem.description)
        )
    }

答案 1 :(得分:0)

你可以加入他们:

($objItem.Name,$objItem.Department,$objItem.Description) -join "|"

这应该可以为您提供所需的输出。

或者你可以使用这样的字符串格式:

"{0}|{1}|{2}" -f $objItem.Name, $objItem.Department, $objItem.Description

编辑:好的,这会在我的机器上运行并返回您想要的结果:

$strFilter = "(&(objectCategory=User)(Description=*MD))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colProplist = "name", "department", "description"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()
$colResults.Properties|%{($($_['name']),$($_['department']),$($_['description'])) -join "|"}