Counting member PER Active Directory Group using Powershell - powershell

Good Morning World
I have written the below Powershell Script which gives me almost what I want.
The error is that this script gives me an incorrect value for the total of members (users).
The incorrect value of members is always 0 (zero).
I need to the number of members (users) PER group.
I welcome your help.
$Groups = (Get-AdGroup -filter 'Name -notlike "Domain Computers"' | select name -expandproperty name)
$Table = #()
$Record = [ordered]#{
"Group Name" = ""
"Name" = ""
"Username" = ""
"Membercount" = 0
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$Record."Membercount" = $Membercount.count
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv C:\MB\GROUP-D.CSV -NoTypeInformation

$Arrayofmembers.Count is the correct parameter. Thanks to
Santiago Squarzon

Related

add exported data from console to csv file

I have script to export users and groups name from active directory to powershell console. Data is exported and it is ok, but Now, I need to add them from console to csv file with columns: Group Name and Users.
Please check below code:
$groups = "first_group","second_group"
ForEach ($Group in $Groups) {
Get-ADGroupMember -identity $group |
Get-ADUser -properties displayName |
Select-Object SamAccountName, displayName, #{name="group";expression={$group}}
}
Please assist to solve it.
**try this **
$groups = "first_group","second_group"
$Table = #()
$Record = #{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name, samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table
$Table | export-csv "C:\Temp\Group.csv" -NoTypeInformation
`
this is the update for distinguishedname
$Record = #{
"Group Name" = ""
"Name" = ""
"Username" = ""
"Group distinguishedName"=""
}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name, samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Group distinguishedName" = (Get-ADGroup -Identity $group).DistinguishedName
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}

Retrieving report of users in Active Directory Security groups

I am trying to search a list of AD security groups and create a report of users in each security group. The report should have the Group Name, Name, UserName and UPN or Email Address.
I found some code that will help me with a majority of this. I need to modify it to display UPN or email address. Also I need to have it recursively search any groups. Currently the major issue I am tackling is displaying all of the information in the security membership object.
$Group = (Get-Content -Path C:\Users\myusername\Documents\test\list.txt)
$Table = #()
$Record = [ordered] #{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -Identity -Group|selectname,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."Username" = $Member.samaccountname
$objRecord = New-Object psobject -Property $Record
$Table += $objrecord
}
}
$Table |export-csv "C:\users\myusername\Documents\securitygroups.csv" -NoTypeInformation
The code is not pulling in all of the objects listed. For example a security group my have 3 users and 1 group listed as members. It looks as thought the script is only displaying the first 2 entries.
Since Get-AdGroupMember does not return userprincipalname or mail, you will need to get that data another way. One way is to call Get-ADUser.
$Record.UserPrincipalName = (Get-ADUser $Member).UserPrincipalName
You can make this slightly more efficient by replacing the New-Object command with the [pscustomobject] type accelerator. Also, you can just output the object in your foreach loop and assign that output to a variable. The way you are doing it (+=) forces PowerShell to expand the variable into memory before doing the reassignment. As the variable stores more and more data, that process becomes increasingly less efficient. The code below reflects the ideas I have mentioned.
$Groups = (Get-Content -Path C:\Users\myusername\Documents\test\list.txt)
$Table = foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -Identity $Group | select name,samaccountname
$Output = foreach ($Member in $Arrayofmembers)
{
[pscustomobject]#{
"Group Name" = $Group
"Name" = $Member.name
"Username" = $Member.samaccountname
"UserPrincipalName" = (Get-ADUser $Member.samaccountname).UserPrincipalName
}
}
$Output
}
$Table | export-csv "C:\users\myusername\Documents\securitygroups.csv" -NoTypeInformation

Get-adgroupmember and Displaying nested group name and its members in and exported to CSV file

I found this script online. It was original designed to get all members of one security group and if there are nested group it will write to the host the nested group name and members in hierarchy form.
I tweaked it to import AD security groups from a CSV file and to export the results to CSV with table format. CSV files has two security group with both security groups has nested groups. Script will only list the users in the second security group and it doesn't list the nested security group.
CSV File format:
Groupname groupad name
test.testdl office\test.testdl test.testdl
test.testsg office\test.testsg test.testsg
Import-Module ActiveDirectory
$GroupList = #{}
$Table = #()
$Record = #{
"Name" = ""
"nested" = ""
"domain" = ""
"userName" =""
}
function Get-GroupHierarchy {
param()
$searchGroups = Import-Csv -Path C:\temp\ad1.csv
foreach ($item in $searchGroups) {
$groupMember = Get-ADGroupMember -Identity $item.Groupname |
Select-Object name, samaccountname, distinguishedName, objectClass
}
}
foreach ($member in $groupMember) {
$username = $member.samaccountname
$distinguishedName = $member.distinguishedName
$dc = [regex]::Match($distinguishedName,'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
$Record."userName" = $member.samaccountname
$Record."Name" = $member.name
$Record."nested" = $member.objectclass
$Record."Domain" = $domainuser
$objRecord = New-Object PSObject -Property $Record
$Table += [array]$objrecord
if ($member.ObjectClass -eq "group") {
$GroupList.add($member.name, $member.name)
Get-GroupHierarchy $member.name
}
Get-GroupHierarchy
}
$Table | Export-Csv "C:\temp\SecurityGroups01.csv" -NoTypeInformation
Error message:
Get-ADGroupMember : Cannot validate argument on parameter 'Identity'. The
argument is null or empty. Provide an argument that is not null or empty, and
then try the command again.
At line:1 char:48
+ $groupMember = Get-ADGroupMember -Identity $item.name | Select-Object name, ...
+ ~~~~~~~~~~
I Know it has been ages since you asked this question. But i was working last week on something similar and obtained some results through some work. I saw this question here working on that piece of work and thought to share my work if it can help somebody.
$members = Get-ADGroupMember 'GroupName'
foreach ($member in $members){
if ($member.objectClass -eq 'Group')
{$NestGroupUsers = Get-ADGroupMember $member | select name, objectclass }
Else {
$hash = [pscustomobject]#{
'name' = $member.name
'objectclass' = $member.objectClass
}
$hash | Export-Csv C:\users.csv -Append -NoTypeInformation
}
}
$NestGroupUsers |Export-Csv C:\users.csv -Append -NoTypeInformation

Get security groups members Domain\Username

I have script that get all members of security groups across domains and export to CSV file in this format: Name, username, security group. But I want to add another row for the domain so format will look like this: domain\username, name, security group.
I could get the DN but I am only interested in just domain\username. I search around in the internet and I couldn't find anything and I am not sure if this even possible
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = #($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name}
$Groups = Import-Csv C:\ad.csv
$Table = #()
$Record = #{ "Group Name" = "" "Name" = "" "Username" = "" }
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group.groupad
-recursive -Server $Domain | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group.ad
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\SecurityGroups3.csv" -NoTypeInformation
As Bum mentioned, you can use a regex to get the DC and combine it with the username:
$username = 'Michael'
$distinguishedName = 'CN=Domain Admins,CN=Users,DC=Fabrikam,DC=com'
$dc = [regex]::Match($distinguishedName, 'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
Output of $domainuser:
$domainuser
Fabrikam\Michael

PowerShell: Get all groups a member belongs to, include group type

I have a script that gives me all members of a group with certain desired information. I want this same format but for all groups that a specified username belongs to. I want information about each group, such as group type (ie security, distribution list). How would I do this? I want a different row for each group, with information about each group in the columns.
Add-PSSnapin Quest.ActiveRoles.ADManagement
$myCol = #()
ForEach ($Group in (Get-QADGroup "CN=research,OU=Security,OU=Groups,DC=xxx,DC=com" -GroupType Security))
{
ForEach ($Member in (Get-QADGroupMember $Group -SizeLimit 0))
{
$myObj = "" | Select Group, Type, Member, Email, Username, Department
$myObj.Group = $Group.Name
$myObj.Type = $Group.groupType
$myObj.Member = $Member.Name
$myObj.Email = $Member.Email
$myObj.Department = $Member.Department
$myObj.Username = $Member.sAMAccountName
$myCol += $myObj
}
}
$myCol | Export-Csv -Path "C:\Users\sdevito\Desktop\test.csv" -NoTypeInformation
or. there is this code that i found that does something similar, but each group is in the same row, different column. i cannot figure out how to edit this code to make each group on a new row.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser sdevito -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File C:\Users\sdevito\Desktop\testt.csv
How about something like:
#Requires -Version 3.0
Add-PSSnapin Quest.ActiveRoles.ADManagement
function Get-UsersGroups {
[cmdletbinding()]
param (
[Parameter(Position=0,Mandatory)][string]$Identity,
[Parameter(Position=1)][ValidateSet('all','nested','normal')][string]$MemberType
)
$user = Get-QADUser -Identity $Identity
switch ( $MemberType ) {
'all' { $groups = $user.AllMemberOf }
'nested' { $groups = $user.NestedMemberOf }
default { $groups = $user.MemberOf }
}
foreach ( $group in $groups ) {
$groupinfo = Get-QADGroup -Identity $group
$props = [ordered]#{
Group = $groupinfo.Name
Type = $groupinfo.GroupType
Member = $user.Name
Email = $user.Email
Department = $user.Department
Username = $user.sAMAccountName
}
$obj = New-Object -TypeName PSObject -Property $props
$obj
}
}
Get-UsersGroups -Identity bob | Export-Csv -Path "C:\Users\sdevito\Desktop\test.csv" -NoTypeInformation