使用PowerShell在更改时复制文件

时间:2013-11-25 17:12:06

标签: powershell filesystemwatcher copy-item

我使用FileSystemWatcher通知文件更改,然后创建该文件的副本:

$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"
}

因此,如果更改C:\Orders\orders.xml,则应创建C:\Orders\backup-20131125121004。但是,这不起作用,并且不会产生错误。通知确实有效,而不是副本:

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 个答案:

答案 0 :(得分:4)

改变这个:

$(watcher.Path)backup-$datestamp"

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

请注意$()内的变量仍然需要$$sender自动变量将始终包含生成事件的对象。