简体   繁体   English

使用 Powershell 列出 AD 中的组和用户数

[英]List groups and number of users in AD using Powershell

I am trying to pull a list of groups from AD that start with "pegp" and a count of how many users are in each group and performing this action in PowerShell. This script will give me a list of the all the groups, but I also need how many users are in each group:我正在尝试从 AD 中提取以“pegp”开头的组列表以及每个组中有多少用户的计数并在 PowerShell 中执行此操作。此脚本将给我所有组的列表,但我还需要每个组中有多少用户:

$groups = Get-ADGroup -Filter "Name -like 'pegp*'"

$Output = forEach($group in $groups) {

    Get-ADGroup -Identity $group | Select-Object name

}

$Output | Export-Csv C:\temp\file_test2.csv

I then tried this code, but it's not giving me a count of the users in each group and is actually inserting an additional row after each group name in the CSV:然后我尝试了这段代码,但它没有给我每个组中的用户计数,实际上是在 CSV 中的每个组名之后插入一个额外的行:

$groups = Get-ADGroup -Filter "Name -like 'pegp*'"

$Output = forEach($group in $groups) {

    Get-ADGroup -Identity $group | Select-Object name
    (Get-ADGroupMember -Identity $group).count
}

$Output | Export-Csv C:\temp\file_test4.csv

Since I'm still new to PowerShell and programming in general, I thought I'd reach out to the well of knowledge to help me figure out where I'm going wrong.由于我对 PowerShell 和一般编程还不熟悉,所以我想我应该利用知识来帮助我弄清楚哪里出错了。 Thanks!谢谢!

Your current code produces an alternating stream of 1 object with a Name property, and 1 integer, which is why Export-Csv is not producing the results you want - it's expecting uniform input.您当前的代码生成一个交替的 stream 1 object 和 Name 属性,以及 1 integer,这就是为什么Export-Csv没有产生您想要的结果 - 它期望统一输入。

What you'll want to do is produce 1 object with 2 properties - for that you could use the Select-Object cmdlet with a calculated property for the member count:您要做的是生成具有2 个属性的 1 object - 为此,您可以将Select-Object cmdlet 与成员计数的计算属性一起使用:

$groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'pegp*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroupMember -Identity $_).Count }}

# no need to call Get-ADGroup again, we already have all the information we need
$groupsWithMemberCount |Export-Csv C:\temp\file_test4.csv -NoTypeInformation

Beware that this counts the total number of members (principals AND nested groups).请注意,这会计算成员总数(主体和嵌套组)。

If you want only users, filter the ouput from Get-ADGroupMember based on their objectClass :如果您只想要用户,请根据他们的objectClass过滤来自Get-ADGroupMember的输出:

$groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'pegp*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroupMember -Identity $_ |Where-Object objectClass -eq 'user').Count}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM