get all groups of user with other user object properties - powershell

I am new to powershell and wanted to learn how to get the groups belonging to a user as well as other user object properties in the format below (repeating the user and email for each group):
username user_email user_groups
user1 user1#domain.com group1
user1 user1#domain.com group2
user1 user1#domain.com group3
user2 user2#domain.com group1
user2 user2#domain.com group2
...
I understand that this gets the groups of a user but unsure of how to include other user objects and have it repeated in the above format:
Get-ADPrincipalGroupMembership username | select name

You'll want to get your ADUser objects, expand their memberof property, iterate through those, and get the ad group of each.
$username = "PowerShellGuy"
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$username'" -properties memberof
$groups = $adUserObj.MemberOf | Get-ADgroup
You can one-line it like this
Get-ADUser -Filter "SamAccountName -eq 'PowerShellGuy'" -properties memberof | % memberof | Get-ADgroup
If you want custom formatting, you can build a custom psobject, or a custom class. I prefer the class method
Class CustomAdInfo
{
$UserName
$Email
$Group
}
If you want one group per, then you can do something like this
Class CustomAdInfo
{
$UserName
$Email
$Group
}
$listOfUsers = #("foo","bar")
$customObjects =
foreach($user in $listOfUsers)
{
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$user'" -properties memberof, emailaddress
$groups = $adUserObj.MemberOf | Get-ADgroup
foreach($group in $groups)
{
New-Object -TypeName CustomAdInfo -Property #{
UserName = $adUserObj.SamAccountName
Email = $adUserObj.EmailAddress
Group = $group
}
}
}

No reason to overcomplicate it. I've added the Get-ADOU call in case you want to use the name of the group instead of the distinguished name.
$ouname = "Some OU"
$OU = Get-ADOrganizationalUnit -Filter "name -eq '$ouname'"
Get-ADUser -Filter * -SearchBase $OU -Properties mail | Foreach-Object {
Foreach($group in Get-ADPrincipalGroupMembership $_)
{
[PSCustomObject]#{
UserName = $_.samaccountname
User_Email = $_.mail
User_Group = $group.name
}
}
}

Related

How to compare users and users in an OU then add the users using Powershell

$Users = Get-ADGroupMember -Identity " Colorado Students" | Get-ADUser -properties SamAccountName
$OU = Get-ADUser -SearchBase ‘OU=Colorado,OU=Middle,OU=Student,OU=Colorado-Users,DC=Colorado,DC=9,DC=CO,DC=US’ -Filter * -Properties SamAccountName
$OU = $OU | Where SamAccountName -notlike $Users
Foreach ($user in $OU) {
Add-ADGroupMember -Identity ‘Colorado Students' -Members $_
}
I am using Powershell 5.0 I am struggling with finishing this one. I want to compare my users to all users in OU then if users are in OU then add.
I believe what you're looking for is to Add all users on the Colorado OU that are currently not members of the Colorado Students group. If that's the case, below code should work:
$groupName = 'Colorado Students'
$adGroup = Get-ADGroup $groupName
$OU = 'OU=someOU,OU=Of,OU=Some,DC=Domain,DC=xyz'
# Look for all users on the OU 'someOU' that are NOT
# MemberOf 'Colorado Students'
$hash = #{
SearchBase = $OU
LDAPFilter = "(!memberOf={0})" -f $adGroup.DistinguishedName
}
$users = Get-ADUser #hash
Add-ADGroupMember -Identity $adGroup -Members $users

Export CSV of AD SamAccountNames and Groups for every user in specific OU

I found a similar question here, but it doesn't quite fit my need and I am having trouble tweaking it to do so.
I need to create a .csv file of all users in a specific OU along with what their AD group membership is in the following format:
User, Group (This is a Header)
User1, Group1
User1, Group2
User1, Group3
User2, Group1
User3, Group1
User4, Group1
User4, Group2
I think this script gets me most of the way there:
$Users = Get-ADGroup -SearchBase "OU=OrgUnit1,OU=OrgUnit2,OU=OrgUnit3,DC=XXX,DC=LOCAL" -Filter * `
| Get-ADGroupMember -Recursive `
| ForEach-Object { Get-ADUser $_ –Properties MemberOf | Select SamAccountName, MemberOf; } `
| Sort-Object SamAccountName
| export-csv C:\Messaging\PowerShell\ADUsers\Test1.csv
The problem with this is two fold.
I want to search on OU=OrgUnit1 without having to search on the full distinguished name, because the sub OU's aren't always the same.
The .csv output has the full distinguished name of the AD Group and I need just the Name of the group with no qualifiers
Use Get-ADOrganizationalUnit to get the OU you want to search:
$ou = Get-ADOrganizationalUnit -Filter "Name -eq 'OrgUnit1'"
Get-ADGroup -Filter * -SearchBase $ou | ...
The memberOf property is a list of groups (or rather their distinguished names). To get the output you want you need to unroll and resolve the group names and create new custom objects with the desired properties:
... | ForEach-Object {
$account = $_.SamAccountName
$_.MemberOf | Get-ADGroup | ForEach-Object {
New-Object -Type PSCustomObject -Property #{
SamAccountName = $account
Group = $_.Name
}
}
} | ...
Also, there's no point in assigning pipeline output to a variable ($Users) if at the end of that pipeline you export the output to a file.
Modified code:
$ou = Get-ADOrganizationalUnit -Filter "Name -eq 'OrgUnit1'"
Get-ADGroup -Filter * -SearchBase $ou |
Get-ADGroupMember -Recursive |
ForEach-Object { Get-ADUser $_ -Properties MemberOf; } |
Sort-Object SamAccountName |
ForEach-Object {
$account = $_.SamAccountName
$_.MemberOf | Get-ADGroup | ForEach-Object {
New-Object -Type PSCustomObject -Property #{
SamAccountName = $account
Group = $_.Name
}
}
} | Export-Csv 'C:\Messaging\PowerShell\ADUsers\Test1.csv'
You don't need this much of code to write. User below code in PowerShell to export all AD user.
Something like this:
Import-Module ActiveDirectory
Get-ADUser -Filter * -Properties * | export-csv c:\ADusers.csv
If you have a big AD, that might take a while though.

Add Users with Active Directory Description Attribute to a group containing the Department Attribute

I try to add every User of an AD with a special description to a group wich contains the Department Attribute (up to 3 digits) as a suffix.
For Example
A User "Sam Test" has the Description "Boss" and the Department "123".
He should be added to Testgroup_123.
My Goal
Write a Script to add the Users to their associated Testgroup_???.
There can only be one Boss(User) in a Testgroup_???.
For testing reasons I only try to output the name.
This is my Code so far:
import-module ActiveDirectory
$user =
Get-ADUser -filter {(description -like "Boss") -or
(description -like "boss") -or
(description -like "Assistant")} -searchbase "OU=TestOU,DC=TE,DC=ADS" -Properties Enabled, description, sAMAccountName, Department | select Department | Foreach {Write-Host "Testgroup_$user<-empty?"}
If I understand your right, try this code:
$Users = Get-ADUser -Filter * -Properties Description,Department
foreach ($user in $Users)
{
if ($user.Description -match "Boss|Assistant")
{
$Dep = $User.Department
if (-not(Get-ADGroup "Testgroup_$Dep"))
{
New-ADGroup -Path "OU=TestOU,DC=TE,DC=ADS" -Name "Testgroup_$Dep" -GroupScope Global
}
else
{
$GroupMembers = Get-ADGroupMember -Identity "Testgroup_$Dep" | Select -ExpandProperty SamAccountName
if ($User.SamAccountName -notin $GroupMembers)
{
Add-ADGroupMember -Identity "Testgroup_$Dep" -Members $User
}
}
}
}
First it gets all the users
Check for each user for description match of "Boss" or "Assistant"
Get the department attribute for the user (just for example 666)
Check if Group name "Testgroup_666" Exist, if not Create new one in the path you defined
Check if the user is not already a member of this group, if not add add the user to the group

Export AD users with list of specific groups

I've been trying to get an extract of AD users and select mail, name, memberof. I then need to list only specific groups from the memberof output so I end up with a list for each user than contains their name, email address and specific groups that match a certain name and not all of the groups they are a member of.
Get-ADUser username -Properties memberof | Select-Object memberof
I can't seem to find a way of doing this as I end up with either noteproperty above or an empty pipeline. Is there a way to achieve what I am trying to do?
The memberOf attribute contains a list of distinguishedName (DN) values, each corresponding to a group.
Retrieve the groups you are interested in, before you run Get-ADUser, that way you can compare the Group DN to the entry in memberOf:
$GroupDNs = Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | Select-Object -ExpandProperty DistinguishedName
Now, you can use those DN's to filter the group memberships with a calculated property, like so:
$UserInfo = foreach($username in #("bob","alice","joe")){
$User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
$User | Select-Object Name,mail,#{Label="GroupDNs";Expr = {$_.memberof | Where-Object {$Groups -contains $_}}}
}
without doing a new Get-ADGroup query for each memberof entry.
If you want a string of group names, rather than a NoteProperty containing an array of strings, you could fill the Groups into a hashtable and use that to "look up" the memberof entries using the ContainsKey() method:
$Groups = #{}
Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | ForEach-Object {
$Groups[$_.DistinguishedName] = $_
}
$UserInfo = foreach($username in #("bob","alice","joe")){
$User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
$User | Select-Object Name,mail,#{Label="Groups";Expr = { ($_.memberof | Where-Object {$Groups.ContainsKey($_)} | ForEach-Object { $Groups[$_].Name}) -join ";" }}
}
$UserInfo | Export-Csv C:\aduserinfo.csv -NoTypeInformation

pull only user name and select groups from AD with Power shell

I want to get all the users in my OU and list only the names of the users that are a member of any group with the word managers in it and list that group or groups they belong to.
So for example
TSmith
Equipment managers
Managers night shift
Bkline
Equipment managers Day Shift
I have been trying to tweak the below script.
The issue is if the user is a member of any group with managers in the name it list everything about that user. All the groups the last log on time everything in AD.
Thanks so much for any help.
Import-Module ActiveDirectory
$users = Get-ADUser -searchbase "OU=East,DC=CHM,DC=com" -Filter * -Properties *
foreach ( $user in $users ) {
$user
$groups = $user | select -ExpandProperty memberof
if ($groups -match 'manager') {
$user.samaccountname
$groups
}
}
Try this:
Get-ADUser -SearchBase "OU=East,DC=CHM,DC=com" -Search -ResultSetSize $null -Filter * -Properties memberOf | Foreach-Object {
# extract grouop names and check if they contain the word 'manager'
$manager = ($_.memberof -replace '^CN=([^,]+),.+$','$1') -like "*manager*"
if($manager)
{
New-Object -TypeName PSObject -Property #{
UserName = $_.SamAccountName
ManagerGroups = $manager -join ';'
}
}
}