newadoualert.ps1

<#PSScriptInfo
 
    .VERSION 1.1
 
    .GUID 477bb663-5ea7-4fc0-814a-b7e3bd8ac144
 
    .AUTHOR Vikas Sukhija
 
    .COMPANYNAME TechWizard.cloud
 
    .COPYRIGHT Vikas Sukhija
 
    .TAGS
 
    .LICENSEURI https://techwizard.cloud/
 
    .PROJECTURI https://techwizard.cloud/
 
    .ICONURI
 
    .EXTERNALMODULEDEPENDENCIES
 
    .REQUIREDSCRIPTS
 
    .EXTERNALSCRIPTDEPENDENCIES
 
    .RELEASENOTES https://techwizard.cloud/
 
 
    .PRIVATEDATA
    ===========================================================================
    Created with: ISE
    Created on: 12/11/2023 1:46 PM
    Created by: Vikas Sukhija
    Organization:
    Filename: newadoualert.ps1
    ===========================================================================
 
#>


<#
 
    .DESCRIPTION
    Monitor and alert when new OU is created or delted in AD
 
#>
 
param()
#################logs and variables##########################
$log = Write-Log -Name "newadoualert" -folder "logs" -Ext "log"
$tempcsv = (Get-Location).Path + "\temp\tempcsv.csv"
$sourcedomain = "DC=lab,DC=labtest,DC=com"

$smtpserver = "smtpserver"
$erroremail = "Reports@labtest.com"
$email1 = "Vikas1@labtest.com","Vikas2@labtest.com" # send alerts to these emails
$from = "DoNotReply@labtest.com"


$logrecyclelimit = 60
$getsnowdate =  get-date -Format "yyyy-MM-ddTHH:mm:ssZ"
#######################get report based on days#################
Write-Log -Message "Start....................Script" -path $log
New-FolderCreation -foldername "temp"
try {
    $sourceOUs = Get-ADOrganizationalUnit -Filter * -SearchBase $sourcedomain -properties WhenCreated | Select DistinguishedName, WhenCreated
    Write-Log -Message "Fetched all OUs - $($sourceOUs.count)" -path $log
    if($($sourceOUs.count) -eq 0){
        Write-Log -Message "No new Ous found" -path $log
        exit
    }
    ##################Start comparing with previous data#################
    if(Test-Path -path $tempcsv){
    $tempimport = Import-Csv $tempcsv
    $change = Compare-Object -ReferenceObject $sourceOUs -DifferenceObject $tempimport -Property DistinguishedName
    $Addition = $change | Where-Object -FilterScript {$_.SideIndicator -eq "<="} 
    $Removal = $change | Where-Object -FilterScript {$_.SideIndicator -eq "=>"} 
    $additioncount = $Addition.DistinguishedName.count
    $Removalcount = $Removal.DistinguishedName.count
    Write-Log -Message "Alert Count Addition - $additioncount" -path $log
    Write-Log -Message "Alert Count Removal - $Removalcount" -path $log
    $recentlycreatedOus = $recentlyremovedOus = $null
    $recentlycreatedOus = $Addition
    $recentlyremovedOus = $Removal
    }else{
        Write-Log -Message "No previous data found" -path $log
        $sourceOUs | Export-Csv $tempcsv -notypeinformation # export to prevous data now
    }
}
catch {
    $exception = $_.Exception.Message
    Write-Log -Message "exception $exception has occured loading Ous" -path $log -Severity Error
    Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error loading Ous - newadoualert" -Body $($_.Exception.Message)
    exit

}
#####################Send Alert to IAM team#################
$error.clear()
try {
    if($recentlycreatedOus.DistinguishedName.count -gt 0){
        foreach($ou in $recentlycreatedOus){
            Write-Log -Message "Send Alert for New OU - $($ou.DistinguishedName)" -path $log
$errmessagebody =@"
      Details:
 
      Created By : $from
      Created By Email : $from
      Notes :
      Reason : Alert - NEW AD OU Created
      OU Name : $($ou.DistinguishedName)
      Status : Open
      Team Name : AD Team
      Support Queue Name : AD Team
      Submit Date : $getsnowdate
"@
           
            Send-MailMessage -SmtpServer $smtpserver -From $afrom -To $snowemail -cc $email1 -bcc $erroremail -Subject "Alert - NEW AD OU Created" -Body $errmessagebody
            if($error){
                Write-Log -Message "Error Occured - $($error)" -path $log
                Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error Occured - newadoualert" -Body $Error[0].ToString()
                Exit
            }
            
        }
        
    }
    #######################removedOus############################
    if($recentlyremovedOus.DistinguishedName.count -gt 0){
        foreach($ou in $recentlyremovedOus){
            Write-Log -Message "Send Alert for Deleted OU - $($ou.DistinguishedName)" -path $log
$errmessagebody =@"
      Details:
 
      Created By : $from
      Created By Email : $from
      Notes :
      Reason : Alert - AD OU Deleted
      OU Name : $($ou.DistinguishedName)
      Status : Open
      PowerApp Form : Alert - AD OU Deleted
      Team Name : AD Team
      Support Queue Name : AD Team
      Submit Date : $getsnowdate
"@
           
            Send-MailMessage -SmtpServer $smtpserver -From $afrom -To $snowemail -cc $email1 -bcc $erroremail -Subject "Alert - AD OU Deleted" -Body $errmessagebody
            if($error){
                Write-Log -Message "Error Occured - $($error)" -path $log
                Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error Occured - newadoualert" -Body $Error[0].ToString()
                Exit
            }
            
        }
        
    }
    $sourceOUs | Export-Csv $tempcsv -notypeinformation # export to prevous data now
}
catch {
    $exception = $_.Exception.Message
    Write-Log -Message "exception $exception has occured loading Ous" -path $log -Severity Error
    Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error loading Ous - newadoualert" -Body $($_.Exception.Message)
    exit

}
##########################Script Finished#################################
Set-Recyclelogs -foldername "logs" -limit $logrecyclelimit -confirm:$false
Write-Log -Message "Script Finished" -path $log
#############################completed####################################