I would like an active directory query to list all users who only belong to "Domain Users" and no other groups.
I already tried the following query, but it showed all users with all groups they belong to:
Import-Module Activedirectory
Get-ADUser -Filter * -Properties DisplayName,memberof | % {
New-Object PSObject -Property #{
UserName = $_.DisplayName
Groups = ($_.memberof | Get-ADGroup | Select -ExpandProperty Name) -join ","
}
} | Select UserName,Groups | Export-Csv C:\temp\report.csv -NTI
Search for an empty memberof-property while PrimaryGroup is "Domain Users". No need to list the groups if you expect nothing.
Get-ADUser -Filter "samaccountname -eq 'froflatest-sshf'" -Properties Memberof, PrimaryGroup, DisplayName, Description |
Where-Object { -not ($_.memberof) -and $_.PrimaryGroup -match 'Domain Users' } |
Select-Object SamAccountName, DisplayName, Description |
Export-CSV -Path "c:\report.csv" -NoTypeInformation
Import-Module Activedirectory
Get-ADUser -Filter "*" -Properties sAMAccountName,Description, Memberof, PrimaryGroup |
Where-Object { -not ($_.memberof) -and $_.PrimaryGroup -match 'Domain Users' } | Select sAMAccountName,Description | Export-Csv C:\temp\report.csv -NTI
Related
I am able to export to users that are not members of particular groups such as IT_Group like below. But, this script gives me all membership of users within memberof column in csv output. If they are members of any groups that matches "IT" they should be displayed within memberof column in csv output like below.
Also , If user is not member to any group that is beginning with IT_ then it will write "any IT group is not member" keyword within memberof column in csv output.
There are 3 security groups such as IT_Group,IT_Group1,IT_Group2
I have tried so far :
Get-ADUser -Filter {(emailaddress -like "*#contoso.com" -and Enabled -eq $false -and sAMAccountName -like "TEST*") -or (emailaddress -like "*#contoso.com" -and Enabled -eq $false -and sAMAccountName -like "PROD*")} -SearchBase "OU=USERS,DC=contoso,DC=com" -SearchScope Subtree -Properties * | Where { [string]$_.memberof -notmatch 'IT_Group'} | Select-Object name , samaccountname ,#{Name="MemberOf";Expression={($_.MemberOf | %{(Get-ADGroup $_).sAMAccountName}) -Join ";"}} |Export-CSV -Path "C:\tmp\output.csv" -NoTypeInformation -Encoding UTF8
My Desired output :
name,samaccountname,memberof
User01,TEST1,IT_Test
User02,PROD1,IT_Prod
User03,TEST4,any IT group is not member
The -Filter should not be written as script block ({..}), but as a normal string.
This should do what you are after:
$filter = "(Enabled -eq 'False' -and EmailAddress -like '*#contoso.com') -and (SamAccountName -like 'TEST*' -or SamAccountName -like 'PROD*')"
Get-ADUser -Filter $filter -SearchBase "OU=USERS,DC=contoso,DC=com" -SearchScope Subtree -Properties EmailAddress, MemberOf | ForEach-Object {
if ($_.MemberOf -match 'CN=IT_(Test|Prod)') {
# the user is a member of any IT_Group, get the names of all groups for this user
$groups = foreach ($grp in $_.MemberOf) { (Get-ADGroup -Identity $grp).Name }
$_ | Select-Object Name, SamAccountName, #{Name = 'MemberOf'; Expression = {$groups -join ', '}}
}
else {
# the user is not a member of any IT_Group
$_ | Select-Object Name, SamAccountName, #{Name = 'MemberOf'; Expression = {'Not a member of any IT_Group'}}
}
} | Export-CSV -Path "C:\tmp\output.csv" -NoTypeInformation -Encoding UTF8
Parsing the name of an object from the DistinghuishedName is tricky, because there can be special characters in there. That is why this code uses the Get-ADGroup cmdlet to get the group names.
If the SamAccountNames do not matter and you want to get ALL users in OU OU=USERS,DC=contoso,DC=com that are not Enabled AND have an EmailAddress ending in #contoso.com, than simply change the $filter variable to
$filter = "Enabled -eq 'False' -and EmailAddress -like '*#contoso.com'"
As per your latest comment, you would only want to list the groups IT_Test and/or IT_Prod for users that are member of any of these two groups, the code below should do that:
$filter = "(Enabled -eq 'False' -and EmailAddress -like '*#contoso.com') -and (SamAccountName -like 'TEST*' -or SamAccountName -like 'PROD*')"
Get-ADUser -Filter $filter -SearchBase "OU=USERS,DC=contoso,DC=com" -SearchScope Subtree -Properties EmailAddress, MemberOf | ForEach-Object {
$testgroups = $_.MemberOf | Where-Object { $_ -match 'CN=IT_(Test|Prod)'}
if ($testgroups) {
# the user is a member of group IT_Test and/or IT_Prod, get the names of these groups for this user
$groups = foreach ($grp in $testgroups) { (Get-ADGroup -Identity $grp).Name }
$_ | Select-Object Name, SamAccountName, #{Name = 'MemberOf'; Expression = {$groups -join ', '}}
}
else {
# the user is not a member of any IT_Group
$_ | Select-Object Name, SamAccountName, #{Name = 'MemberOf'; Expression = {'Not a member of any IT_Group'}}
}
} | Export-CSV -Path "C:\tmp\output.csv" -NoTypeInformation -Encoding UTF8
Hope that helps
This code get all users that have groups begining with "IT_" it's provided by $_.memberof -like 'CN=IT_*'.Then for each user getting his name,login and groups what beggins from"CN=IT_",format it with -replace and add it to csv file without rewrite.
$users=Get-ADUser -Filter {filter options} -Properties MemberOf| Where-Object { $_.memberof -like '*CN=IT_*'}
foreach ($user in $users){
$user|Select-Object name , samaccountname ,#{Name="MemberOf";Expression={((($_.MemberOf | Select-String -Pattern 'CN=IT_*')-replace "CN=")-replace ",.+$") -Join ";"}} |Export-CSV -Delimiter ';' -Path "D:\testdir\uss.csv" -NoTypeInformation -Encoding UTF8 -Append
}
I have a list of users (their CN), and I want a list of the groups they are member of.
I already have a code which almost does the trick, but it shows as follows:
User1 - group1;group2
User2 - group1;group2;group3 etc...
Also, groups are shown as distinguished name (with container etc), so very long. I only want the name.
I want to show it as follows:
User1 - group1
User1 - group2
User2 - group1, etc
The code that shows the groups the users are member of, but not in the visual way i like is below:
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$User = Get-ADUser -filter "CN -eq '$($_.CN)'" -properties memberof
[PSCustomObject]#{
SourceCN = $_.CN
MemberOf = $User.MemberOf -join ";"
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
.\Output.csv
I have some other code that list the groups how I want, but I am unable to list it per user. And unable to combine it with the above code.
get-aduser -filter {cn -eq "Testuser"} -properties memberof |
Select -ExpandProperty memberof |
ForEach-Object{Get-ADGroup $_} |
Select -ExpandProperty Name
Thanks in advance :)
You could combine both code pieces like this:
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$user = Get-ADUser -Filter "CN -eq '$($_.CN)'" -Properties MemberOf, CN -ErrorAction SilentlyContinue
foreach($group in $user.MemberOf) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = (Get-ADGroup -Identity $group).Name
}
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
Edit
Although I have never seen an AD user to have no group membership at all (should have at least the default Domain Users in the MemberOf property), You commented that you would like to have a test for that aswell.
Import-Csv -Path .\Input_CN.csv |
ForEach-Object {
$user = Get-ADUser -Filter "CN -eq '$($_.CN)'" -Properties MemberOf, CN -ErrorAction SilentlyContinue
if (!$user) {
Write-Warning "No user found with CN '$($_.CN)'"
# skip this one and resume with the next CN in the list
continue
}
$groups = $user.MemberOf
if (!$groups -or $groups.Count -eq 0) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = 'No Groups'
}
}
else {
foreach($group in $groups) {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = (Get-ADGroup -Identity $group).Name
}
}
}
} | Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
This is a bit clunky, but you can use nested loops:
Import-Csv -Path .\Input_CN.csv | ForEach-Object {
$user = Get-ADUser -filter "CN -eq '$($_.CN)'" -properties cn, memberof
$user | ForEach-Object {
$_.MemberOf |
ForEach-Object {
[PSCustomObject]#{
SourceCN = $user.CN
MemberOf = $_.split('[=,]')[1]
}
}
}
} | Where-Object {$null -ne $_.MemberOf} |
Export-Csv -Path .\Output.csv -Delimiter ";" -NoTypeInformation
UPDATE: Updated to show only the 'CN' part of the group name and to filter any users who are not a member of any group.
All in one line could be
Get-ADUser -filter {Enabled -eq $True} -Properties Name, Created | Select-Object Name, Created, #{Name="Groups";Expression={Get-ADPrincipalGroupMembership -Identity $_.SamAccountName | Where-Object {$_.GroupCategory -Eq 'Security'} | Join-String -Property Name -Separator ", "}}
I have a list with AD groups in a CSV file: Input_ADGroup.csv
Column A looks like this:
CN
ADgroup1
ADgroup2
I already have some code which list all the users of the groups in the output.csv file, however I am missing the ADgroup name. So it is unclear which users are member of which group.
$Manager = #{Name = "Manager"; Expression = {%{(Get-ADUser $_.Manager -Properties DisplayName).DisplayName}}}
$Manager_Location = #{Name = "Manager_Location"; Expression = {%{(Get-ADUser $_.Manager -Properties Office).Office}}}
$Fields = #(
'SamAccountName'
'CN'
'DisplayName'
'Office'
'mail'
'Department'
$Manager
$Manager_Location
)
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
So is it possible to get a column which shows the "source-ADgroup"... or another format which breaks the list with the ADGroup name or something?
IMO my other suggested solution is more efficient applyig the same CN from the input:
$Data = ForEach($CN in (Import-Csv -Path H:\Test\Input_ADGroup.csv).CN) {
Get-ADGroup -Filter "CN -eq '$CN'" -Properties CN -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -Properties * | Select-Object ($Fields+#{n="Group";e={$CN}})
}
$Data
$Data | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
As you already have AD group name in $_, you can add one more calculated property to your Select-Object by changing this:
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
to this (saving first group name to variable to not mix up with $_ used later in pipeline):
$GroupName = $_.CN
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$GroupName}})
Credits to #LotPings and #Maikel for pointing out the issue with incorrect $_ usage in comments
NOTE: remember about brackets, otherwise you'd receive an error like:
Select-Object : A positional parameter cannot be found that accepts argument n="Group";e={$GroupName}
#Lotpings #robdy - Thanks for your input, I got it working so many thanks. See code below
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties CN -PipelineVariable name -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$name}})
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
One last note: The AD group gets displayed as CN=Groupname,OU=...OU=… etc
I couldn't get it to show just "Groupname" but this really is not an issue.
I'm trying to generate a report for all disabled accounts that don't have the group "Terminated Employees" but it isn't seeming to generate the report. Below is the code that I have at the moment.
TLDR: The text file contains a list of all the disabled accounts and I am trying to cross reference that list with the list of people in Terminated Employees and then return to a CSV file the accounts that are in that list and not in the group "Terminated Employees".
Also note that we need to bypass the limit of Get-ADGroupMember as there are over 5000 members in this group.
$ADGroupName = "Terminated Employees"
$users = Get-Content C:\Shortcuts\users.txt
$InputPath= "C:\Scripts\T_Accounts.csv"
$a = #(Get-ADGroup $ADGroupName | Select-Object -ExpandProperty Member)
foreach ($user in $users) {
if ($a -contains $user) {
"Member found"
} else {
$SplitStep1 = ($Member -split ",",2)[0]
$SplitStep2 = ($SplitStep1 -split "=",2)[1]
$SplitStep2 = $SplitStep2 | Out-File -Append $InputPath
}
}
foreach ($value in (Get-Content $InputPath)) {
$b = Get-ADUser -Identity $value -Properties DisplayName, sAMAccountName, LastLogonDate, Enabled
}
I suggest using Import-Csv and Export-Csv cmdlets handling input and output files. And if we are searching disabled user accounts, which are members of specific group, there should be no need for the input file at all.
How about this oneliner:
Get-ADGroup "Terminated Employees" -Properties Members |
Select-Object -ExpandProperty Members |
Get-ADUser -Properties Enabled, Displayname, LastLogonDate |
Where-Object {$_.Enabled -eq $false} |
Select-Object DisplayName, SamAccountName, LastLogonDate, Enabled |
Export-Csv outfile.txt
Edit: Should have internalized the original question before rushing to answer. I think the clearest way is to create two sets of users and compare them, exporting results to CSV file.
$disabledusers = Get-Aduser -filter "Enabled -eq '$false'" -properties
DisplayName, SamAccountName, LastLogonDate, Enabled | select DisplayName,
SamAccountName, LastLogonDate, Enabled
$groupmembers = Get-ADGroup "Terminated Employees" -Properties Members|
Select-Object -ExpandProperty Members | Get-ADUser -Properties DisplayName,
sAMAccountName, LastLogonDate, Enabled | select DisplayName, SamAccountName,
LastLogonDate, Enabled
Compare-Object $groupmembers $disabledusers -Property enabled -PassThru |
?{$_.sideindicator -eq "=>"} | select DisplayName, SamAccountName,
LastLogonDate, Enabled | export-csv outfile.txt
You aren't requesting the Members property from ActiveDirectory in your Get-ADGroup command (also need to add the s to Members in your Select-Object ;) ).
$ADGroupName = "Terminated Employees"
$users = Get-Content C:\Shortcuts\users.txt
$InputPath= "C:\Scripts\T_Accounts.csv"
# Here we need to add the -Properties parameter to ask ActiveDirectory for the group Members
$a = #(Get-ADGroup -Identity $ADGroupName -Properties Members | Select-Object -ExpandProperty Members)
ForEach ($user in $users)
{
if ($a -contains $user)
{
"Member found"
}
else
{
$SplitStep1 = ($Member -split ",",2)[0]
$SplitStep2 = ($SplitStep1 -split "=",2)[1]
$SplitStep2 = $SplitStep2 | out-file -Append $InputPath
}
}
ForEach ($value in (Get-Content $InputPath))
{
$b = Get-ADUser -identity $value -Properties DisplayName, sAMAccountName, LastLogonDate, Enabled
}
I am trying to create a powershell to audit new created accounts & groups and who created them. The objects are created by account operators, but they are not domain admins.
I think something like this:
$Last = (Get-Date).AddDays(-1);
Get-Acl | Get-ADUser -Filter {WhenCreated -ge $Last} | FL DistinguishedName, Path,owner
But this doesn't work yet.
This one liner will let you know about the changes after a certain date. There is a whenchanged property with which you can filter down the objects.
Get-ADObject -Filter 'whenchanged -gt $dte' | Group-Object objectclass
then you can use :
get-adgroup -filter * | sort name | select Name
Get-adgroupmember "Name"
or
Get-ADGroup -filter "GroupCategory -eq 'Security'" –properties Member |
Select Name,#{Name="Members";
Expression={($_.member | Measure-Object).count}},
GroupCategory,GroupScope,Distinguishedname |
Out-GridView -Title "Select one or more groups to export" -OutputMode Multiple |
foreach {
Write-Host "Exporting $($_.name)" -ForegroundColor cyan
#replace spaces in name with a dash
$name = $_.name -replace " ","-"
$file = Join-Path -path "C:\work" -ChildPath "$name.csv"
Get-ADGroupMember -identity $_.distinguishedname -Recursive |
Get-ADUser -Properties Title,Department |
Select Name,Title,Department,SamAccountName,DistinguishedName |
Export-CSV -Path $file -NoTypeInformation
Get-Item -Path $file
}