Powershell Script to compare files in two different locations and for any change happen it should trigger an alert to email

Ashok Kumar Busi 1 Reputation point
2022-09-12T07:56:27.103+00:00

I am having same files in two paths "/home/azureadmin/HTML" and "/var/www/html". I want to trigger an email alert when there is a file change by comparing the files in the locations mentioned. For this can anyone help with a powershell script. Please

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,504 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 46,551 Reputation points
    2022-09-12T14:30:18.773+00:00

    Try this (I haven't tested it):

    $path1 = "/home/azureadmin/HTML"  
    $path2 = "/var/www/html"  
    Get-ChildItem -Path $path1 -File |  
        ForEach-Object{  
            $name2 = "{0}\{1}" -f $path2, $_.Name  
            $hash1 = Get-FileHash -Path $_.FullName -Algorithm SHA256  
            $hash2 = Get-FileHash -Path $name2 -Algorithm SHA256  
            if ($hash1 -ne $hash2){  
                # send email here  
            }  
        }  
    

    It doesn't cover the case of a file existing in one directory and not in the other. It only uses the file in one directory to compare against a file with the same name in another directory.

    0 comments No comments

  2. Limitless Technology 39,586 Reputation points
    2022-09-12T19:57:47.29+00:00

    Hello there,

    You need Task Scheduler in addition to Powershell to achieve you trigger the mail.

    Use PowerShell to Compare Two Files https://devblogs.microsoft.com/scripting/use-powershell-to-compare-two-files/
    Easily Compare Two Folders by Using PowerShell https://devblogs.microsoft.com/scripting/easily-compare-two-folders-by-using-powershell/

    You can also trigger mail when an Event ID is generated.

    The Send-MailMessage cmdlet sends an email message from within PowerShell.

    You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage command fails.

    ----------------------------------------------------------------------------------------------------------------------------------

    --If the reply is helpful, please Upvote and Accept it as an answer–

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.