Check current user group membership - powershell

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"
}

Related

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
}
}
)

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

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"
}}

How to fix the remove from group function

I am trying to make a script that will add and remove computers from a group if they are in a specific ou. What I have so far adds the computers and then when run again it removes all computers from the group. Then run it again and it adds them all back.
It should add the computers that are in the OUs and remove the computers that have been moved out of the OU
$OUSTUCOMPUTERS = "OU=STUDENT,OU=Computers,DC=domain,DC=local"
$OUConstruction = 'BCT','Carpentry','Electrical Occupations','HVAC'
$List = #{}
$Group=[ADSI]"LDAP://CN=CompStuConstruction,OU=Computer Groups,OU=Computers,DC=domain,DC=local"
foreach ($Shop in $OUConstruction)}
{$Distinguishedname = "OU="+"$Shop"+","+"$OUSTUCOMPUTERS"
$OU = [ADSI]"LDAP://$distinguishedname"
# Enumerate all objects in the OU.
$arrChildren = $OU.Children
ForEach ($Child In $arrChildren)
{
# Only consider computer objects.
If ($Child.Class -eq "computer")
{
# Add all computers in the OU to the hash table.
$List.Add($Child.distinguishedName, $True)
# Check if user a member of the group.
If ($Group.IsMember($Child.ADsPath) -eq $False)
{
# Add the computers to the group.
$Group.Add($Child.ADsPath)
"Added " + $Child.distinguishedName
}
}
}
}
# Enumerate all members of the group.
ForEach ($Member in $Group.member)
{
# Check if this member object is a computer object in the OU.
If ($List.ContainsKey($Member)-eq $False)
{
# Remove this member from the group.
$Group.Remove("LDAP://$Member")
"Removed " + $Member
}
}
I would suggest to use the ActiveDirectory module instead of [ADSI]. Then do
# get your group
$group = Get-ADGroup -Identity "your group"
# clear group
Remove-ADGroupMember -Identity $group -Members #(Get-ADGroupMember -Identity $group)
# add back only correct computer objects
Add-ADGroupMember -Identity $group -Members #(Get-AdComputer -Filter * -SearchBase "your ou" -SearchScope Subtree)

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"

Returning Unique user Id in GrantSendOnBehalfTo attribute in the Get-Mailbox cmdlet

I'm pulling out details for Delegate details of mailboxes from Office 365 setup using the exchange shell.
The problem is I'm getting the Display name of users in the GrantSendOnBehalfTo attribute of the Mailbox which isn't unique a value. How to print the unique ID of users in the GrantSendOnBehalfTo attribute?
I cannot test this right now, but I think this may help:
$SendOnBehalf = Get-Mailbox -Identity 'testing' | Select-Object -ExpandProperty GrantSendOnBehalfTo
foreach ($user in $SendOnBehalf) {
try {
# get the user or group that has SendOnBehalf permissions
$sob = Get-User -Identity $user -ErrorAction SilentlyContinue
if ($sob) {
Write-Host "User: $($sob.SamAccountName)" # or use $($sob.WindowsEmailAddress) if that is more unique for you
}
else {
$sobGroup = Get-Group -Identity $user -ErrorAction SilentlyContinue
Write-Host "Group: $($sob.SamAccountName)"
}
}
catch {}
}