Scripting - Watch changes for a file and send an email notification

525 views Asked by At

Hi All I am new to scripting. I am trying to send an email notification when ever the file is changed.

I tried to use the below script just to get a notification if the file is changed but how do I do it every time the file changes. Below script works only for one time so I have put it into an infinite loop to notice changes when ever the file is changed but, I know its not an ideal way to do it. I also need to send an email. How do i do that. Appreciate your responses. Thank you.

while (1 -eq 1)
{$File = "C:\Test\test.log"
$Action = 'Write-Output "The watched file was changed"'
$global:FileChanged = $false

function Wait-FileChange {
    param(
        [string]$File,
        [string]$Action
    )
    $FilePath = Split-Path $File -Parent
    $FileName = Split-Path $File -Leaf
    $ScriptBlock = [scriptblock]::Create($Action)


    $Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }
    $onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}

    while ($global:FileChanged -eq $false){
        Start-Sleep -Milliseconds 100
    }

    & $ScriptBlock 
    Unregister-Event -SubscriptionId $onChange.Id
}

Wait-FileChange -File $File -Action $Action
}
1

There are 1 answers

0
Mike Garuccio On

The script itself does not have to keep runnning in order for the events to be triggered, they are registered in the powershell host and will keep watching your files until that console is closed. so the below would actually work if you opened a powershell window and ran something like below (obviously you need to define your variables and such still) then just left the console open (doing this as a background task becomes a bit trickier)

$Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
    IncludeSubdirectories = $false
    EnableRaisingEvents = $true
}
Register-ObjectEvent $Watcher Changed -Action $Action