You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用PowerShell执行Get-ADGroup仅返回1000条记录求解决方案

问题原因

Active Directory域服务默认配置了LDAP查询单请求返回结果上限为1000条,仅设置-ResultPageSize仅调整单页拉取的条数,没有解除总结果数的限制,所以最多只能拿到1000条记录。

解决方案

在原PowerShell命令中新增-ResultSetSize参数并赋值为$null,即可解除总返回条数限制,修复后完整代码如下:

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript("Get-ADGroup -filter * -ResultPageSize 5120 -ResultSetSize $null");

    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
    foreach (PSObject obj in PSOutput)
    {
        if (obj != null)
        {
            Console.WriteLine(obj.Properties["DistinguishedName"].Value.ToString());
            Console.WriteLine(obj.Properties["GroupCategory"].Value.ToString());
            Console.WriteLine(obj.Properties["GroupScope"].Value.ToString());
            Console.WriteLine(obj.Properties["Name"].Value.ToString());
            Console.WriteLine(obj.Properties["ObjectClass"].Value.ToString());
            Console.WriteLine(obj.Properties["SamAccountName"].Value.ToString());
        }
    }
}

可选优化建议

  • 可以在PowerShell脚本中提前用Select-Object过滤需要返回的属性,减少序列化和数据传输开销,命令可调整为:Get-ADGroup -filter * -ResultPageSize 5120 -ResultSetSize $null | Select-Object DistinguishedName,GroupCategory,GroupScope,Name,ObjectClass,SamAccountName
  • 建议补充PowerShell调用的异常捕获逻辑,处理权限不足、域控连接中断等异常场景
  • 如果后续需要处理更大规模的AD对象查询,可直接使用C#原生System.DirectoryServices命名空间下的类操作AD,性能和稳定性都优于调用PowerShell实例

内容的提问来源于stack exchange,提问作者Lynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 12:51:01