如何在 PowerShell 中实现此代码中的分页查询?

问题描述 投票:0回答:1

我有一段使用命名空间 System.DirectoryServices.Protocols.LdapConnection 的代码。但是,我尝试实现的分页不起作用(仅返回前 500 个项目)。你能告诉我出了什么问题吗?

$ldapFilter = "(&(objectClass=group)(|(cn=CAX_*)(cn=F_*)(cn=G_*)))"
$results = @()
$pageSize = 500

try {
    # Conectar ao servidor LDAP
    Write-Host "Iniciando conexão com o servidor LDAP..." -ForegroundColor Cyan
    $ldapConnection = New-Object System.DirectoryServices.Protocols.LdapConnection "ldap"
    $ldapConnection.SessionOptions.SecureSocketLayer = $false
    $ldapConnection.SessionOptions.ProtocolVersion = 3
    $ldapConnection.AuthType = [System.DirectoryServices.Protocols.AuthType]::Negotiate

    Write-Host "Conectando ao servidor LDAP..." -ForegroundColor Green

    # Configurar paginação
    Write-Host "Configurando controle de paginação com tamanho de página: $pageSize" -ForegroundColor Cyan
    $pageControl = New-Object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize)
    $searchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest("DC=ldap,DC=com", $ldapFilter, "Subtree", "cn", "info", "description")
    $searchRequest.Controls.Add($pageControl)

    $morePages = $true

    while ($morePages) {
        # Enviar requisição de busca
        Write-Host "Enviando requisição de busca ao servidor LDAP..." -ForegroundColor Cyan
        $searchResponse = $ldapConnection.SendRequest($searchRequest)
        #Write-Host "Buscando grupos com o filtro: $ldapFilter" -ForegroundColor Green

        # Verificar resultados
        Write-Host "Processando resultados da página atual..." -ForegroundColor Cyan
        foreach ($entry in $searchResponse.Entries) {
            Write-Host "Processando entrada: $($entry.Attributes["cn"][0])" -ForegroundColor Yellow
            $results += [PSCustomObject]@{
                Name        = $entry.Attributes["cn"][0]
                Info        = if ($entry.Attributes["info"].Count -gt 0) { $entry.Attributes["info"][0].Replace("r", "").Replace("n", "") -split "n" } else { "" }
                Description = if ($entry.Attributes["description"].Count -gt 0) { $entry.Attributes["description"][0] } else { "" }
            }
        }

        # Verificar se há mais páginas de resultados
        Write-Host "Verificando se há mais páginas de resultados..." -ForegroundColor Cyan
        $pageResponseControl = $searchResponse.Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.PageResultResponseControl] }
        if ($pageResponseControl -and $pageResponseControl.Cookie.Length -gt 0) {
            Write-Host "Mais páginas encontradas, continuando a busca..." -ForegroundColor Cyan
            $pageControl.Cookie = $pageResponseControl.Cookie
            $searchRequest.Controls.Clear()
            $searchRequest.Controls.Add($pageControl)  # Atualizar o controle de página na requisição de busca
        } else {
            Write-Host "Nenhuma outra página encontrada, finalizando busca." -ForegroundColor Cyan
            $morePages = $false
        }
    }

    Write-Host "Total de grupos encontrados: $($results.Count)" -ForegroundColor Green
} catch {
    Write-Host "Erro ao conectar ou buscar no LDAP: $_" -ForegroundColor Red
}

$adGroups = $results

# Se nenhum grupo foi encontrado, informe e saia do script
if ($adGroups.Count -eq 0) {
    Write-Host "Nenhum grupo encontrado. Verifique o filtro ou a conexão com o LDAP." -ForegroundColor Yellow
}

# Definir o caminho do arquivo JSON
$jsonPath = "C:\temp\GPAD\grupos_ad.json"
Write-Host "Exportando dados para o arquivo JSON em: $jsonPath" -ForegroundColor Cyan

# Exportar os dados para JSON
$adGroups | ConvertTo-Json | Set-Content -Path $jsonPath -Encoding UTF8

Write-Host "Dados exportados para o arquivo JSON em: $jsonPath" -ForegroundColor Green

输出:

Code output

我想获得所有的AD组。只带来了500人,却有1000多个团体。我感谢您的帮助!

powershell ldap
1个回答
0
投票

如何在 PowerShell 中在此代码中实现分页查询?中所建议的,显式传递

[System.DirectoryServices.Protocols.SearchOption]::DomainScope
以及搜索请求可能会解决此处出现的任何潜在问题。

using namespace System.DirectoryServices.Protocols

# ...
# construct the search request just like you currently are
$searchBaseDN = 'DC=ldap,DC=com'
$attributesToFetch = @(
  'cn'
  'info'
  'description'
)
$searchRequest = [SearchRequest]::new($searchBaseDN, $ldapFilter, "Subtree", $attributesToFetch)

# add the page control, same as now
$pageControl = [PageResultRequestControl]@{ PageSize = $pageSize }
[void]$searchRequest.Controls.Add($pageControl)

# ... and then additionally add an explicit search option control
$searchOptionsControl = [SearchOptionsControl]@{ SearchOption = 'DomainScope' }
[void]$searchRequest.Controls.Add($searchOptionsControl)

注意:我稍微重写了代码,以利用

using namespace ...
指令来缩短类型名称。对于低于 5.0 的 PowerShell 版本,您仍然需要使用
New-Object System.DirectoryServices.Protocols.<type>
而不是
[<type>]@{ ... }
/
[<type>]::new(...)
来进行对象实例化。

© www.soinside.com 2019 - 2024. All rights reserved.