I used the below code for pulling out AD group of users
$users = Get-Content u:\users.txt
ForEach ($User in $users) {
$user1 = Get-ADUser -Identity $User -Properties *;
$GroupMembership = ($user1.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
$User1.SamAccountName + ';' + $GroupMembership >>test4.csv
}
I would like to add a filter which fetches the only particular type of ad group say starting with SG
I had tried putting a filter but it gave me a boolean true or false but not the filtered value.
You want to filter the Name property starting with SG?, try this:
Get-ADGroup -filter 'Name -like "SG*"'
Related
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 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.
edited from original question because the real problem was something unrelated to the question
I got a list of trustees from NTFS permissions and now I want to expand the groups to show membership. If I have a SAM name like MyDomain\name, there's no indication of whether that is a group or not. The Get-ADobject command has an ObjectClass property which will indicate group or user if this is an Active Directory domain object. One can use:
Get-ADObject -filter 'SamAccountName -eq "My Users"' or
$sam = "My Users"
Get-ADObject -filter 'SamAccountName -eq $sam'
Thanks to JPBlanc who had an alternate form of writing that with a script block and some other suggestions.
And thanks, user2142466. That looks like a good suggestion for my original script.
You can use a variavle using :
$sam = "My Users"
Get-ADObject -Filter {(SamAccountName -eq $sam)}
But I agree that using vars in -Filter sometimes results in strange behaviours with vars (see this question), so I prefer to use -LDAPFilter.
Get-ADObject -LDAPFilter "(SamAccountName =$user)"
Be careful the -LDAPFilter use polish notation for the filter, it's a bit disconcerting at the begining, but here, it's the natural way of filtering using the underlaying protocol LDAP.
You can get more information about this syntax in Search Filter Syntax, you can also get corresponding filters in About_ActiveDirectory_Filter.
I am guessing you are getting an array of trustees. (i.e User,Group,user,user,Group). So if you get a group then you want to pull the members from it too?
So I would look to see if it is a group, like how you are doing first and then pulling those members out of it. Add it to an another array which will contain every single user for your NTFS permissions.
$arraytrustees
#Create a blank Array
$NTFSUsers =#()
for each ($object in $arraytrustees){
$ObjectClass = (Get-ADObject -filter {SamAccountName -eq $object}).ObjectClass
If ($ObjectClass -eq "group"){
$AdGroupUsers = (Get-ADGroupMember -identity $object).SamAccountName
$NTFSUsers = $NTFSUsers + $AdGroupUsers
}else{
$NTFSUsers = $NTFSUsers + $ojbect
}
}
I was asked to list all members of the groups, along with their ID, Name, and Description as well, so I added a couple of lines.
cls
$Users = #()
$Groups = #()
$list = Get-Content z:\pcm2.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
If ($ObjectClass -eq "User")
{
$U = Get-ADUser -Properties * -Identity $o
$User = "" | Select FullUserName, LoginID, Description
$User.FullUserName = $U.DisplayName
$User.LoginID = $U.SamAccountName
$User.Description = $U.description
$Users += $User
}
Else
{
If ($ObjectClass -eq "Group")
{
$G = Get-ADGroup -Properties * -Identity $o
$GM = Get-ADGroupMember -Identity $G.name -Recursive | Get-ADUser -Properties *
Foreach ($gmember in $GM)
{
$Group = "" | Select GroupName, GroupDescription, GroupMemberName, GroupMemberLoginID, GroupMemberDesc
$Group.GroupName = $G.Name
$Group.GroupDescription = $G.Description
$Group.GroupMemberName = $gmember.Name
$Group.GroupMemberLoginID = $gmember.SamAccountName
$Group.GroupMemberDesc = $gmember.Description
$Groups += $Group
}
}
}
}
$Users | Export-Csv z:\PCMUsers.csv -NoTypeInformation
$Groups | Export-Csv z:\PCMGroups.csv -NoTypeInformation
I received a list and was asked to determine whether the objects were users or group, and I came up with this. It worked!
cls
$Users = #()
$Groups = #()
$list = Get-Content z:\pcm.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
If ($ObjectClass -eq "User")
{
$U = Get-ADUser -Properties * -Identity $o
$User = "" | Select FullUserName, LoginID, Description
$User.FullUserName = $U.DisplayName
$User.LoginID = $U.SamAccountName
$User.Description = $U.description
$Users += $User
}
Else
{
If ($ObjectClass -eq "Group")
{
$G = Get-ADGroup -Properties * -Identity $o
$Group = "" | Select GroupName, Description
$Group.GroupName = $G.Name
$Group.Description = $G.Description
$Groups += $Group
}
}
}
$Users | Export-Csv z:\Users.csv -NoTypeInformation
$Groups | Export-Csv z:\Groups.csv -NoTypeInformation
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 ';'
}
}
}