4

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked great! Thanks, I didn't know about $sender. My completed script is here for reference: github.com/mrichman/bizsync/blob/master/WatchBizSyncOrders.ps1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.