Not sure if anyone can assist. I have a script which pulls from AD all users not part of a Security group. This script uses $excludeOUs to exclude OU's with accounts which don't need to be in this group. However when i run this it seems to generate a few accounts mainly Healthmailbox but the OU they sit in it seems to show them in the report. Is there some form of command that needs to be added to exclude these.
# create a regex from an array of OUs to exclude by 'OR-ing' them with the pipe character
$excludeOUs = ('OU=Exchange','OU=Support Accounts','OU=Terminated Users and Computers do not use',
'OU=TerminatedEmployeesContractors','OU=TestAccounts','OU=Contractors and Consultants',
'OU=MIS Users and Groups','OU=Service Accounts','OU=Security Groups','OU=Users',
'OU=Testing','OU=Microsoft Exchange System Objects','OU=Microsoft Exchange Security Groups',
'OU=CorpServiceAccounts','OU=Elevated','OU=***','OU=*** Assets','OU=Monitoring Mailboxes','OU=Users','OU=Q_Users','OU=Microsoft Exchange System Objects' | ForEach-Object {[Regex]::Escape($_)}) -join '|'
$ExportPath = 'c:\app\UsersNotinSG.csv'
# get a list of objects not having any of the excluded OUs in their DistinguishedName
# and at the same time output objects with properties 'User' and 'Groups'
$grp=(Get-ADGroup 'SG_********').DistinguishedName
Get-ADUser -Filter { -not (memberof -eq $grp) -and (enabled -eq $true) } -Properties MemberOf |
Where-Object {$_.DistinguishedName -notmatch $excludeOUs} |
Select-Object #{Name = 'User'; Expression = {$_.Name}},
#{name = "OU";expression={$_.DistinguishedName.split(',')[1].split('=')[1]}}|
Export-Csv $ExportPath -NoTypeInformation
Thanks
HealthMailboxes* are in CN=Monitoring Mailboxes rather than OU= – AdminOfThings
Related
Good Afternoon
I am trying to create a PS script which pulls all users not in a certain Security group. I have managed to get this to work fine. However i require it to omit certain OU's as i don't want certain accounts included in this process like terminated users and support accounts for examples.
So i created the below to do this but it seems to fail. Its where i have tried to add some filtering. Can someone help put this in the right direction?
import-Module activedirectory
$results = #()
$users = Get-ADUser -Properties memberof -Filter {enabled -eq $true} | ? {$_.DistinguishedName -notlike "*,OU=Exchange,OU=Support Accounts,OU=Terminated Users and Computers do not use,OU=TerminatedEmployeesContractors,OU=TestAccounts*"} *
$ExportPath = 'c:\app\users_in_ou1.csv'
foreach ($user in $users) {
$groups = $user.memberof -join ';'
$results += New-Object psObject -Property #{'User'=$user.name;'Groups'= $groups}
}
$results | Where-Object { $_.groups -notmatch 'SG_XXXXXXXXXXX' } | Select-Object user | export-csv $ExportPath
Thanks
I would build a regex from all OUs that should be excluded from the search by joining the strings with the regex 'OR' character (|) and use the -notmatch operator.
Because there may be characters in these strings that have special meaning in regex, use [Regex]::Escape() on each before joining them.
Something like below:
Import-Module ActiveDirectory
# create a regex from an array of OUs to exclude by 'OR-ing' them with the pipe character
$excludeOUs = ('OU=Exchange','OU=Support Accounts','OU=Terminated Users and Computers do not use',
'OU=TerminatedEmployeesContractors','OU=TestAccounts' | ForEach-Object {[Regex]::Escape($_)}) -join '|'
$ExportPath = 'c:\app\users_in_ou1.csv'
# get a list of objects not having any of the excluded OUs in their DistinguishedName
# and at the same time output objects with properties 'User' and 'Groups'
$users = Get-ADUser -Properties Name, MemberOf -Filter 'Enabled -eq $true' |
Where-Object {$_.DistinguishedName -notmatch $excludeOUs} |
Select-Object #{Name = 'User'; Expression = {$_.Name}},
#{Name = 'Groups'; Expression = {($_.MemberOf -join ';')}}
# next filter this out further by excluding a certain group and export to Csv
$users | Where-Object { $_.Groups -notmatch 'SG_XXXXXXXXXXX' } | Export-Csv $ExportPath -NoTypeInformation
I'm working on a script that takes all the users in the AD and getting four specifics.
saMAccountName
Displayname
Comment
Specific group name (Group A)
Below is the code that I have now. It works, but it gives me all the groups, I only need one specific group (Group A) to be listed.
If the user is not a member of this group, the user must be listed in the export but without the listing of the group
Get-ADGroup -Filter {name -like "Domain Users"} |
Get-ADGroupMember | Where-Object { $_.objectClass -eq 'user' } |
Get-ADUser -Properties comment,displayname,MemberOf |
select saMAccountName,displayname,comment,#{Name="MemberOf";Expression={$_.MemberOf -Join ";"}} |
Sort-Object SamAccountName | Export-csv -path C:\Install\Export-AD.csv -NoTypeInformation
Hope you have some tips and pointers for me on how to filter on the group name.
You could just add a comparison operation (-like) to your expression for MemberOf. You can see an example of this below. However, I would recommend against that single augmentation because of the inefficient nature of the Where-Object and the unnecessary queries that are happening here.
Get-ADGroup -Filter {name -like "Domain Users"} | Get-ADGroupMember | Where-Object { $_.objectClass -eq 'user' } | Get-ADUser -Properties comment,displayname,MemberOf | select saMAccountName,displayname,comment,#{Name="MemberOf";Expression={($_.MemberOf -like "Group A") -join ";"}} | Sort-Object SamAccountName | Export-csv -path C:\Install\Export-AD.csv -NoTypeInformation
I don't know how efficiently this runs in your AD. I tested this with a 722 member group, and it took 22.221 seconds to run.
I would try something like this instead as it will be significantly faster:
$GroupFilterDN = (Get-ADGroup "DOMAIN users").DistinguishedName
$GroupCheck = (Get-ADGroup "Group A").DistinguishedName
Get-ADUser -filter {(memberof -eq $GroupFilterDN -or PrimaryGroup -eq $GroupFilterDN) -and (ObjectClass -eq "user")} -Properties comment,displayname,MemberOf |
select saMAccountName,displayname,comment,#{Name="MemberOf";Expression={$_.MemberOf.where({$_ -in $GroupCheck}) -join ";"}} |
Sort-Object SamAccountName | Export-csv -path C:\Install\Export-AD.csv -NoTypeInformation
You need to replace the Group A string with your group name in the $GroupCheck variable.
$GroupFilter contains the group you want to filter on. In your example, you wanted to filter on Domain Users. The variable holds the DN for that group.
$GroupCheck contains the group for which you want to find members. The variable holds the DN for that group. In your example, you called this Group A.
The PrimaryGroup check had to be added since in your example you are using Domain Users. Domain Users does not show up in the MemberOf property.
The where({$_ -in $GroupCheck}) method is for when $GroupCheck has multiple groups. $GroupCheck currently would only have one group, but it could be tweaked to have multiple.
The code removes the requirement of using the Get-ADGroupMember command, which contains the Where-Object. Then it adds a comparison operation (-eq) for the MemberOf expression.
I tested the second block of code and it completed in 3.847 seconds with the same 722 member group.
I need some assistance in modifying the script below to List any AD User account that is disabled outside of the specific OU.
$filter = '(Enabled -eq $false)'
$ResultDirectory = 'C:\Disabled-ADAccountOutsideOU.csv'
$domainDN = (Get-ADDomain).DistinguishedName
$excludeOUs = #(
'OU=Site1,OU=Disabled Users'
'OU=Site2,OU=Disabled Users'
'OU=SiteX,OU=Disabled Users'
) | ForEach-Object { $_ + ',' + $domainDN }
Get-ADUser -Filter $filter -Properties * |
Where-Object { ($_.SamAccountName.Length -eq 7) -and ($excludeOUs -notcontains $_.ParentContainer) } |
Select-Object -Property SamAccountName, Enabled, #{n='ParentContainer';e={$_.DistinguishedName -replace '\A.*?,(?=(CN|OU|DC)=)'}}, CanonicalName, LastLogonDate |
Export-Csv -NoTypeInformation -Path $ResultDirectory
Because at the moment, the problem is the script is exporting some of the users accounts inside the OU=SiteX,OU=Disabled Users OU and nothing is exported or listed under the Default OU CN=Users,DC=Domain,DC=com where some of the Disabled AD account is there?
I'm trying to query Active Directory to get a list of all users and all groups each user is a member of. I only need the direct groups each user is a member of, not the nested groups. The end-goal is to output this list to a CSV file. I'm attempting to do this using PowerShell in Windows Server 2012 R2.
UPDATE
So I've now managed to output a list of all users' names, however only some of the users's groups are included in the output, using the following command:
Get-ADuser -LDAPFilter "(objectClass=user)" -property "memberOf" |
select -Property #{n='name';e={$_.name}},#{n='groups';e
{$($_.MemberOf | Get-adgroup | % {$_.name}) -join ','}}
I'm unable to determine why only some of the users output (probably only 5-10 total) include the groups the user is a member of, while the rest (95%) of the users output only display the name of the user, without any groups at all.
Any ideas from here?
First of all I'am afraid that Get-ADuser -Filter {group -eq 'Domain Users'} just give nothing.
You can try to begin :
Get-ADuser -LDAPFilter "(objectClass=user)" -property "memberof" | select -Property #{n='name';e={$_.SamAccountName}},#{n='groups';e={$_.MemberOf -join ','}}
Then you can modify the filter to also take InetOrgPerson.
Get-ADuser -LDAPFilter "(|(objectClass=user)(objectClass=inetOrgPerson))" -property "memberof" | select -Property #{n='name';e={$_.SamAccountName}},#{n='groups';e={$_.MemberOf -join ','}}
Then you can take the samAccountName of the group DN
Get-ADuser -LDAPFilter "(|(objectClass=user)(objectClass=inetOrgPerson))" -property "memberof" | select -Property #{n='name';e={$_.SamAccountName}},#{n='groups';e={$($_.MemberOf | Get-adgroup | % {$_.SamAccountname}) -join ','}}
Late reply to this post, but I built a script that output all Groups in a specific OU and all users of each group. Only downside is that the "owner" of each group is also a member, so there is a bit of redundancy, but nothing breaking for my purpose. The output is formatted into two columns.
$mGroups=#(
Get-ADGroup -filter * -SearchBase "OU=,OU=,OU=,DC=,DC=" | select name);
$col = #()
for ($i=0
$i -lt $mGroups.Count;
$i++)
{
$agents=#(
Get-ADGroupMember $mGroups[$i].name | select sAMAccountName)
for ($n=0
$n -lt $agents.Count;
$n++)
{
$agentList = [PSCustomObject]#{
Group = $mGroups[$i].name
Agents = $agents[$n].sAMAccountName
}
$col+=$agentList;
}
}
$col
$col | Export-CSV -NoTypeInformation C:\Path\to\file.type
I have taken the code snipits from many sites, and almost have what I need. The only problem is I need to just return groups that are of GroupCategory Security.
I am trying to search an OU in Active Directory, return the users and then list each Security group they are a member of, sorted by name (both user and then the groups they belong to). Output that to txt file
$FilePath = 'C:\'
$EndDate = (Get-Date).tostring("yyyyMMdd")
$FileName = 'GroupMembership By User - ' + $EndDate + '.txt'
$Users=Get-ADUser -Filter * -Properties * -SearchBase "OU=My Accounts,DC=DOMAIN,DC=COM" | sort-object -property Name
ForEach ($User in $Users) {
$GroupMembership = ($User.memberof | foreach-object {(Get-ADGroup $_).Name ;}) -join ',';
$User.Name + ',' + $GroupMembership #|out-file -append "$FilePath$FileName"
}
#| Where-Object {$_.GroupCategory -EQ "Security"}
My output is comma delimited and sorted by username on each line, but I can't seem to get the groups sorted (less important overall) nor the Group listing to exclude the Distribution groups (must have). THe last line commented out, will return just security groups, but no matter where I put it, it doesn't work or fails the command.
TIA
How about this then. You had the logic in a comment. I guess you were not sure where to put it. I also remove some of the redundancy in creating $GroupMembership
$Users | ForEach-Object {
$GroupMembership = $_.memberof | Get-ADGroup | Where-Object{$_.GroupCategory -eq "Security"} | Sort-Object Name | Select -ExpandProperty Name
(#($_.Name) + $GroupMembership) -join ","
} | Add-Content $FilePath$FileName
To try and use the pipeline without an errors I changed your ForEach construct. This way we can tack on the Add-Content at the end of the pipe.
$GroupMembership is populated with the output of Get-AdGroup and we remove the distribution groups* with your Where-Object clause. A simple sort and expand leaves us with just the group names.
* I have to experiment but I'm not sure how that reacts to mail enabled security groups.