Check if a device is NOT a member of a specific group

With this PowerShell script you can check if a device is NOT a member of a specific group. A colleague and I created this script because our AD computers should be a member of 1 out of 3 AD groups. If the device is not member of one of these groups certain group policy’s wont be loaded and some thing won’t work properly. With the results of this script we know that devices have to be added to a AD group to function properly.

#Created by Dave Rozenblad 30-06-2020
#Modified by Remy Kuster 06-07-2020
#Script to check if a AD computer is NOT a member of certain groups based on a search of a specific AD OU.
#If the device is NOT a member of a specific group a email will be send so that a sysadmin can correct the membership of the device.

#Create the variables of the AD groups that you want to be checked, you can quote out groups if you only want to check 1 or 2 groups.

$Group1 = Get-ADGroup -Identity 'give-in-the-ad-groupname-here'
$Group2 = Get-ADGroup -Identity 'give-in-the-ad-groupname-here'
$Group3 = Get-ADGroup -Identity 'give-in-the-ad-groupname-here'

#Create the variable with the devices that do not have got the group membership(s). Based on a specific AD Organizational Unit, and with an exclude of certain OU's under the searchbase OU if you unquote the -notlike lines below.

 $list = Get-ADComputer -Filter *  -SearchBase "OU=Devices,DC=domain,DC=nl" -Properties MemberOf | 
Where-Object {
    ( $_.MemberOf -notcontains $Group1.DistinguishedName ) -and
    ( $_.MemberOf -notcontains $Group2.DistinguishedName ) -and
    ( $_.MemberOf -notcontains $Group3.DistinguishedName ) -and
    #($_.DistinguishedName -notlike "*OU=CYOD,OU=Cleanup,OU=Department,OU=Devices,DC=domain,DC=nl") -and
    #($_.DistinguishedName -notlike "*OU=Apple,OU=Devices,DC=domain,DC=nl") -and
    #($_.DistinguishedName -notlike "*OU=Voorraad,OU=Devices,DC=domain,DC=nl") -and
    #($_.DistinguishedName -notlike "*OU=CYOD,OU=Devices,DC=domain,DC=nl")
} |
Select-Object -Property DistinguishedName

#Send an email to a certain mail address IF a device is found without the group membership. If you don't want a mail to be send just quote out the section below and unquote the $ list variable at the bottom.

If ($list.DistinguishedName -like "*OU=Devices,DC=domain,DC=nl") {

$smtpServer = ""
$to = ""
$smtpFrom = ""
$smtpTo = $to
$messageSubject = "There are device without the groups $Group1, $Group2 or $Group3"
$messageBody ="The following devices are missing the correct group membership:`n",$list.DistinguishedName ,"`n Please add the device to the correct AD group(s)" | Out-String

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)


Theme: Overlay by Kaira