Search code examples
powershellfilesystemwatchercopy-item

Copying a file on change using PowerShell


I am using a FileSystemWatcher to notify on file change, and then create a copy of that file:

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Orders\"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

$changed = Register-ObjectEvent $watcher "Changed" -Action {
   write-host "Changed: $($eventArgs.FullPath)"
   $datestamp = get-date -uformat "%Y%m%d%H%M%S" 
   write-host $datestamp
   copy-item $eventArgs.FullPath "$(watcher.Path)backup-$datestamp"
}

Thus, if C:\Orders\orders.xml is changed, then C:\Orders\backup-20131125121004 should be created. However, this is not working, and not producing errors. The notification does work, just not the copy:

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Documents and Settings\sladministrator\Desktop> .\WatchBizSyncOrders.ps1
PS C:\Documents and Settings\sladministrator\Desktop> Changed: C:\Orders\New Text Document.txt
20131125100821

Solution

  • Change this:

    $(watcher.Path)backup-$datestamp"
    

    to

    $($sender.Path)backup-$datestamp"
    

    Note that the variable inside the $() still needs a $. And the $sender automatic variable will always contain the object that generated the event.