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 ';'
}
}
}
Related
Was wondering if you could help me with script.
This script would search a specific OU (let's say Disabled Users OU) and display all the AD groups
all users are part of, the output to a CSV file showing Usernames and AD group names.
I have got a command that will display all AD groups of a user but I have to keep changing the username:
Get-ADPrincipalGroupMembership username_withoutdomain | select name
I have a script that requires the username entered and will display the AD group membership.
do {
write-host -NoNewline "Type username: "
$user = read-host
if ($user -eq "") { break }
(get-aduser $user -Properties memberof).memberof |
get-adgroup |
select -exp name
} while ($true)
I also know it is possible to do this via command prompt:
net userusername
Thanks for all assistance.
You can query all users under an OU by using the -SearchBase parameter, from there you can enumerate each user and then enumerate each group the user is a memberOf to generate your report:
$base = 'OU=disabledUsers,DC=domain,DC=com'
Get-ADUser -Filter * -SearchBase $base -Properties memberOf |
ForEach-Object {
foreach($group in $_.memberOf) {
[pscustomobject]#{
User = $_.Name
SamAccountName = $_.SamAccountName
MemberOf = $group -replace '^CN=|(?<!\\),.+'
}
}
} | Export-Csv path\to\report.csv -NoTypeInformation
As Santiago already stated you can query your OU with the -SearchBase.
And because the user and the group membership can not be queried with one command you have to create a table as Santiago points with [pscustomobject]#{...}
When I was running a daily report on users and their group membership I was running the script:
function Get-ADUserGroups{
#$Domain = 'Domain_name'
$users= Get-AdUser -Filter * -Properties SamAccountName, DisplayName, Description -ResultPageSize 500 |
select SamAccountName, DisplayName, Description
$users|
ForEach-Object{
$p=[ordered]#{
UserName=$_.SamAccountName
FullName=$_.DisplayName
User_Description=$_.Description
GroupName=$null
Group_Description=$null
}
Get-ADPrincipalGroupMembership $_.SamAccountName |
ForEach-Object{
$p.GroupName=$_.Name
Get-ADGroup $_ -Properties description |
ForEach-Object{
New-Object PsObject -Property $p
}
}
}
}
Get-ADUserGroups | Export-Csv -Path "Your_Path\Groups.csv" -Delimiter "|" -Encoding UTF8 -NoTypeInformation
I'm tryng to get all the groups the users of a domain are member of, but filtering only the groups with a given extensionattribute.
I set the extensionattribute12 of all the domain groups to better filter some queries (i.e. Infrastructure - security - elearning). My query should get only the user(s) groups with
extensionattribute12=security
(for example).
I use something like:
get-aduser -filter -Properties memberof | select name, #{ l="GroupMembership"; e={$_.memberof -join ";" } }
and I get all the groups of the users. How can I filter by group extensionattribute?
You could use the inverse relationship (member on the group object) to query all the groups a user is a member of, just 1 query per user. Here using an LDAP filter:
$groupLabel = "Security"
Get-ADUser -Filter * |ForEach-Object {
$groups = Get-ADGroup -LDAPFilter "(&(extensionattribute12=$groupLabel)(member=$($_.DistinguishedName)))"
[pscustomobject]#{
User = $_.SamAccountName
GroupMembership = $groups.DistinguishedName -join ';'
}
}
If you have to process a large number of users or group memberships, you may find it faster to retrieve all the groups satisfying the extensionAttribute12 criteria up front and use that list to filter the memberOf attribute on the users:
$groupLabel = "Security"
# Create a hash set and populate it with the distinguished
# names of all the groups we're looking for
$groupDNs = [System.Collections.Generic.HashSet[string]]::new(#(
Get-ADGroup -Filter "extensionAttribute12 -eq '$groupLabel'" |Select -Expand DistinguishedName
))
Get-ADUser -Filter * -Properties memberOf |ForEach-Object {
# Retrieve memberOf values and filter against the hash set
$groups = $_.memberOf |Where-Object { $groupDNs.Contains($_) }
[pscustomobject]#{
User = $_.SamAccountName
GroupMembership = $groups -join ';'
}
}
Make it with N+1 queries
$groups = #( Get-ADGroup -Filter '(extensionattribute12 -eq "security")' )
$users = #( $groups |
ForEach-Object { Get-ADGroupMember -Identity $_ -Recursive } |
Sort-Object -Unique )
$users # All users of all groups that have EA12 = security
Get-ADUser -filter {...} -Properties memberof | select name, #{ l="GroupMembership"; e={( $_.memberof | Get-ADGroup |?{ $_.extensionattribute12 -eq 'security' }) -join ";" }} |?{ $_.GroupMembership }
I'm trying to figure out the logic to do something like this:
Query all AD groups in a specific OU
Query all the users in a specific OU
Query all the user's group memberships
If any user belongs to one or more groups in the initial group query, output that information
If any user belongs to none of the groups in the initial group query, also output that information
I've dug around on this site and found a script that works for the most part, but I'm stuck on how I can compare the user's group membership to the original group query that I'm pulling. It looks like I could use the compare-object cmdlet but the parameters don't seem to include anything that would let me keep track of how many groups the two objects have in common.
The code I found online is below:
$groups = Get-ADGroup -Filter * | where {$_.distinguishedname -like "*,OU=TUNE_TEST_GROUPS,OU=TUNE_TEST,DC=tune,DC=priv"}
$users = Get-ADUser -Filter * | where {$_.distinguishedname -like "*,OU=TUNE_TEST_USERS,OU=TUNE_TEST,DC=tune,DC=priv"}
foreach ( $User in $Users ) {
$userGroups = Get-ADPrincipalGroupMembership $User
if ( $userGroups.Count -gt 1 ) {
"{0} is a member of the following {1} groups:" -f $User.SamAccountName, $userGroups.Count
foreach ( $group in $userGroups ) {
"`t{0}" -f $group.Name
}
} elseif ( $userGroups.Count -lt 1 ) {
"{0} is a member of the following {1} groups:" -f $User.SamAccountName, $userGroups.Count
foreach ( $group in $userGroups ) {
"`t{0}" -f $group.Name
}
}
}
The problem with this is that I don't have a way of comparing the user group names to the names of the group query in line 1. I also can't determine that a user belongs to 1 or more groups from that list. I'm not sure if I can use the same count method.
You can validate that accounts are member of at least one group from your reference list by using Compare-Object:
foreach ( $User in $Users ) {
$userGroups = Get-ADPrincipalGroupMembership $User
if (!(Compare-Object $userGroups $groups -IncludeEqual -ExcludeDifferent)) {
"{0} doesn't belong to any reference group." -f $User.SamAccountName
}
}
Side note: use the -SearchBase parameter instead of filtering the results of Get-ADUser and Get-ADGroup by a wildcard match on the distinguished name:
$groups = Get-ADGroup -Filter * -SearchBase 'OU=TUNE_TEST_GROUPS,OU=TUNE_TEST,DC=tune,DC=priv' -SearchScope Subtree
$users = Get-ADUser -Filter * -SearchBase 'OU=TUNE_TEST_USERS,OU=TUNE_TEST,DC=tune,DC=priv' -SearchScope Subtree
I ended up doing the following and it works well for what I need. In case anyone is interested, sample code is below:
#gets a list of all groups in a given OU and stores the objects in the $groups variable
$groups = Get-ADGroup -Filter * -SearchBase 'OU=TUNE_TEST_GROUPS,OU=TUNE_TEST,DC=tune,DC=priv' -Properties name | select name
#pipe each group object into a foreach loop and output a string value of the same group name and stores it into the $groups_string variable
$groups_string = $groups | % {$_.name}
#gets a list of all users in a given OU and stores the objects in the $users variable
$users = Get-ADUser -Filter * -SearchBase 'OU=TUNE_TEST_USERS,OU=TUNE_TEST,DC=tune,DC=priv'
$results=#{
"Username" = ""
"Groupname" = ""
}
$table=#()
#iterates through every user in the $users variable and retrieves their group memberships
foreach ($user in $users) {
#selects each group name and stores it in the $groupMembership variable
$groupMembership = Get-ADPrincipalGroupMembership $user | select name
#compares the names of each user's group to the baseline group name.
$groupMembership | foreach ($_) {
#If there is a match add the group name and the username to the $results hash table
if ($groups_string -contains $_.name) {
$results."Groupname" = $_.name
$results."Username" = $user.Name
#create a new PS object and supply the properties of the $results hash table to each object
$objresults = New-Object psobject -Property $results
#add each object to the $table array
$table += $objresults
}
}
}
#display/output the $table array and format it to fit
$table | ft -AutoSize
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
I got a list of 150+ users and I want to know which group they have membership for?
I just started using PS. I can query for 1 user, but not for a list of users. Would like
to know exact command??? I got :
(get-aduser -identity "username" -properties memberof |select-object memberof).memberof > c:\temp\ss.csv
Read your user list into an array and check if your AD users are contained in that array:
$userlist = Get-Content 'C:\your\userlist.txt'
Get-ADUser -Filter '*' -Properties memberof | Where-Object {
$userlist -contains $_.SamAccountName
} | ForEach-Object {
$username = $_
$groups = $_ | Select-Object -Expand memberof |
ForEach-Object { (Get-ADGroup $_).Name }
"{0}: {1}" -f $username, ($groups -join ', ')
} | Out-File 'c:\temp\ss.csv'
Replace SamAccountName as appropriate if the user list doesn't contain the account names of the users.