Thriller bad accounts. Need help! (powershell - Active Directory) - powershell

Using powershell I must check on each Administrator user that they are only a member of a particular group and not of other groups.
Of course since the Active Directory.
I have an order that allows me to make a list of accounts that are related to the group, but it doesn’t work:
$users = Get-QADUser ""nom du compte""
$group = Get-QADGroupMember ""nom du group""
$members = Get-QADGroupMember -Identity $group | Select -ExpandProperty Name
ForEach ($user in $users) {
If ($members -contains $user) {
Write-Host "$user exists in the group"
} Else {
Write-Host "$user not exists in the group"
}}

Related

PowerShell: Trying to find which users are not members of a list of groups

In our organization we have job title groups for multiple reasons and I'm trying to find which users have no group assigned. The groups and users are stored in the same OU in AD. There are groups for the departments containing "department" in the title, so I'm excluding those, as they are nesting all the job title groups for a department, and there are no users, which are direct members. This is what I came up with so far, but sometimes I receive duplicate results like the function is running several times against the same entry and I don't understand why.
cls
$SearchBase = "OU DN"
$ErrorActionPreference = "Continue"
$Groups = Get-ADGroup -SearchBase $SearchBase -Filter 'Name -notlike "*department*"' | Select -ExpandProperty Name
$Users = Get-ADUser -SearchBase $SearchBase -Filter * | Select -ExpandProperty Name | sort
$TotalItems = $Users.Count
$CurrentItem = 0
$PercentComplete = 0
function Get-JTGroups($User) {
foreach ($Group in $Groups) {
$int = 0
Try {
$Members = Get-ADGroupMember -Identity "$Group" -Recursive | Select -ExpandProperty Name -ErrorAction Stop
}
Catch {
Write-Host $_.Exception.Message
}
if ($Members -contains $User) {
$int = 1
Write-Host "$User has JT group"
}
}
if ($int = 0) {
Write-Host "$User has no JT group"
}
}
foreach ($User in $Users) {
Write-Progress -Activity "Checking JT Groups members, hold on." -Status "$PercentComplete% Complete:" -PercentComplete $PercentComplete
Get-JTGroups $User
$CurrentItem++
$PercentComplete = [int](($CurrentItem / $TotalItems) * 100)
}
Is there a way to avoid duplicated entries and can this code be optimized?
Thanks in advance
I believe this task would be easier, faster and more efficient by leveraging the filtering capabilities of Active Directory. Your current code as is will be tremendously slow because you're getting the recursive membership of all the groups in $groups for each user in $users. Instead you can ask AD to find all users who are not a recursive member of any of the groups in $groups.
$filter = '(&'
Get-ADGroup -SearchBase $SearchBase -Filter 'Name -notlike "*department*"' | ForEach-Object {
$filter += '(!memberOf:1.2.840.113556.1.4.1941:={0})' -f $_.DistinguishedName
}
$filter += ')'
$allUsersNotRecursiveMemberofGroups = Get-ADUser -LDAPFilter $filter
For details on LDAP Filter see Active Directory: LDAP Syntax Filters.

remove terminated users from DISTRIBUTION groups in AD

I am working on a solution that will help keep our Active Directory clean, so I want to use a Powershell script that will remove the disabled accounts from all groups.
I got the following script:
foreach ($username in (Get-ADUser -SearchBase "OU=Terminated Users,DC=corp,DC=company,DC=com" -filter *)) {
# Get all group memberships
$groups = get-adprincipalgroupmembership $username;
# Loop through each group
foreach ($group in $groups) {
# Exclude Domain Users group
if ($group.name -ne "domain users") {
# Remove user from group
remove-adgroupmember -Identity $group.name -Member $username.SamAccountName -Confirm:$false;
# Write progress to screen
write-host "removed" $username "from" $group.name;
# Define and save group names into filename in c:\temp
$grouplogfile = "c:\temp\" + $username.SamAccountName + ".txt";
$group.name >> $grouplogfile
}
}
}
It's working fine but only for security groups. Users are not deleted from distribution groups. I searched the Internet and people mostly suggest to use "Remove DistributionGroup Member" cmdlet. However, this is the Exchange cmdlet and we use Google Workspace for our email, so this cmdlet is not recognized when I run it on the DC.
Any idea how to solve it? Thanks!
The cmdlet Remove-ADPrincipalGroupMembership will help:
#get all disabled users in specified OU
$disabledUsers = get-aduser -SearchBase "OU=test_piotr,DC=corp,DC=company,DC=com" -LDAPFilter '(userAccountControl:1.2.840.113556.1.4.803:=2)' -Properties memberof,samaccountname
#Loop through array and remove groupmembership and store operation result in $result
$result = #(
foreach ($user in $disabledusers){
try {
#Only process user account if memberships are present
If ($user.memberof){
#Remove all memberships the user has currently, no need to exclude domain users as $user.memberof does not return it
$null = Remove-ADPrincipalGroupMembership -Identity $user.samaccountname -MemberOf $user.memberof -Confirm:$false -ErrorAction:stop
write-host "Removed user: $($user.samaccountname) from groups: $($user.memberof -join ',')"
#Build object for logfile, you could also loop through $user.memberof to create one object per removed group
$attrsHt = #{
smaccountname=$user.samaccountname
group=($user.memberof -join ',')
status='removed'
exception=$null
}
New-Object -typename psobject -Property $attrht
}
}
Catch {
write-error "Failed to remove user: $($user.samaccountname) from groups: $($user.memberof -join ',') - Exception: $_"
$attrsHt = #{
smaccountname=$user.samaccountname
group=($user.memberof -join ',')
status='error'
exception=$_
}
New-Object -typename psobject -Property $attrht
}
}
)

Check current user group membership

I'm looking to check current user group membership and run the script based on that. This script runs. However, it requires RSAT Active Directory tools to run.
I would like to run this script as a GPO. Does anyone have any ideas?
Thanks in advance.
###########################################################################################
# Check AD group Membership
###########################################################################################
$user = "$env:UserName"
$groups = 'FM-TMASQLUserAccess'
foreach ($group in $groups) {
$members = Get-ADGroupMember -server **servernamehere** -Identity $group -
Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $user) {
Write-Output "$user is a member of $group"
}
Else {
Write-Output "$user is not a member of $group"
}
}
For the current logged in user, specifically, you don't need to explicitly query AD - the users security token already contains all the group memberships resolved at logon, so you can do:
$groupName = 'FM-TMASQLUserAccess'
# Fetch identity information about current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
# Grab group SIDs from the users token
$groupTokenSIDs = $currentUser.Groups
# Translate the SID references to account/group names
$Groups = $groupTokenSIDs |Where-Object { $_.AccountDomainSid } |ForEach-Object { $_.Translate([System.Security.Principal.NTAccount]) }
# Test if list contains target group
if($Groups |Where-Object { $_.Value -like "*\$groupName" }){
"$env:USERNAME is a member of $groupName"
}

Filtering AD Group by User Properties ; Returning improperly

Disclaimer: I am not good with powershell, this in mainly butchered code. I apologize if this is done poorly or is a stupid question.
I am trying to filter the ACTIVE users in my company by their company (ET) and whether or not they are in a certain group.
So the filter for ACTIVE users in the company "ET" is working properly, the output of this script gives me every active users with that parameter; it does not filter it further down into only users in a certain group.
$users = Get-ADUser -filter {(Enabled -eq $True) -and (Company -eq "ET")}
-SearchBase 'DC=CSOKI,DC=Local' |select -exp samaccountname
$group = "O365-E3-Full"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -
ExpandProperty samaccountname
ForEach ($user in $users) {
If ($members -contains $user) {
Write-output $(name) | out-file ".\TEST.txt"
} Else {
Write-Host "$user does not exist in the group"
}}
Expected:
Output ACTIVE users in company ET that are in group O365-E3-FULL and write-host users that are not(unnecessary, I just want the filter).
Actual:
Write-hosts every ACTIVE user in company ET and ignores the group filter.
In getting your list of users you are collecting the account name for the users with:
| Select -exp samaccountname
Then in getting group members you are getting the Name with:
| Select -ExpandProperty Name
You need to be selecting SamAccountName in both of your Gets
Sorry, pretty quick knock together
# Create empty array
$answer = New-Object System.Collections.ArrayList
# If is in group then add to array
If ($members -contains $user) {
$answer.Add($user) > $null
} Else {
Write-Host $user "does not exist in the group"
}
# Output the array to the text file
Write-output $answer | out-file ".\TEST.txt"

Powershell import-csv

Creating a script that checks if a list of users from csv file are in a specific AD Group
Import-Module ActiveDirectory
$userscsv = Import-Csv C:\User-list.csv
$group = "testgroup"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
ForEach ($user in $userscsv) {
If ($members -contains $user) {
Write-Host "$user exists in the group"
} Else {
Write-Host "$user does not exists in the group"
}}​
In my csv file i have the names in A1 A2 A# etc I get this format bellow:
#{Johnny Walker=Alex Hood} does not exists in the group
I added
$userscsv = Import-Csv C:\User-list.csv | select -ExpandProperty User
It worked, if you guys have some feedback and tweaking, I'm all ears