AD搜索输出中不需要的换行符

时间:2013-06-14 15:47:55

标签: powershell active-directory

我遇到了输出问题;我想再看看另一种让我的输出没有返回或新行的方法。

有人可以帮我看一下吗?

$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Workstations");

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher;
$objSearcher.SearchRoot = $objDomain;
$objSearcher.PageSize = 100000;
$objSearcher.SearchScope = "Subtree";

$dateMonth = Get-Date -Format "MM";
$dateDay = Get-Date -Format "dd";
$dateYear = Get-Date -Format "yyyy";

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

$colResults = $objSearcher.FindAll();

foreach ($objResult in $colResults)
    {

        $objItem = $objResult.Properties; 

        $computer = $objItem.name | Select-String -Pattern 'NSC';


        Write-Host $computer;

        #Add-Content "C:\PowerShell\Reports\Computer Report - $dateMonth-$dateDay-$dateYear.csv" "$computer";
    }

示例输出:



NSCNPR02





NSCNPR05

NSCNPR01


NSCNPR03

预期输出:

NSCNPR03
NSCNPR05
NSCNPR01
NSCNPR03

3 个答案:

答案 0 :(得分:1)

试试这个:

$date = Get-Date -Format "MM-dd-yyyy"
$filename = "C:\PowerShell\Reports\Computer Report - $date.csv"

...

$objSearcher.FindAll() | ? {
  $_.Properties.Name -like 'NSC*'
} | Add-Content $filename

您的代码存在的问题是

Add-Content "C:\Pow...csv" "$computer"
即使$computer$null

也会添加新行。此行为是由$computer周围的双引号引起的。如果没有它们,问题就不会存在(但我的建议仍然是一个更清洁的解决方案;)。

答案 1 :(得分:0)

Add-Content添加新行。 作为一种解决方法,您可以将文本输出到字符串中,然后在循环完成后将其写入文件。

答案 2 :(得分:0)

您可以使用LDAP过滤而不是拉动所有记录然后搜索吗?

而不是

"LDAP://OU=Workstations"

使用

"LDAP://OU=Workstations?(&(objectCategory=computer)(name=NSC*))"

有关详细信息:http://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx