Powershell + Robocopy 自动备份执行多次

Powershell + Robocopy Auto backup executing multiple times

我已经将这个脚本放在一起来检测目录中的文件更改,这样只要更改生效,更改的文件就会立即得到备份。

我也设置了邮件通知。

备份有效。我可以看到每当文件更改时它都会被复制到所需的目的地,但是我收到了三封电子邮件并且 robocopy 日志没有显示任何更改,这让我认为每次文件更改时它都会被写入三次。所以最后一次写的当然不会有任何变化。

下面是代码,希望大家帮我看看是怎么回事。

#The Script
$folder = 'C:\_Using Last Template Approach\' # Enter the root path you want to monitor.
$filter = '' # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $false if required. 
$fsw = New-Object IO.FileSystemWatcher $folder -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Changed -SourceIdentifier AutoBackUp -Action {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$datestamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
$Computer = get-content env:computername
$Body = "Documents Folders have been backed up"
robocopy "C:\_Using Last Template Approach" G:\BackUp\  /v /mir /xo /log:"c:\RobocopyLog.txt"
Send-MailMessage -To "me@me.com" -From "jdoe@me.com" -Subject $Body -SmtpServer "smtp-mm.me.com" -Body " "


# To stop the monitoring, run the following commands (e.g using PowerShell ISE:
# Unregister-Event AutoBackUp
}

我不会更改您的监控脚本,只是更改发送邮件并使用 copy-item powershell 命令进行复制

$folder = 'c:\sites' # Enter the root path you want to monitor. 
$filter = '*.*'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white 
Out-File -FilePath c:\sites\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
$username=”gmailaccount”
$password=”password”
$smtpServer = “smtp.gmail.com”
$msg = new-object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential( $username, $password )
$msg.From = "gmail"
$msg.To.Add(“mail should check notify”)
$msg.Body=”Please See archive for notification”
$msg.Subject = “backup information”
$files=Get-ChildItem “c:\sites\filechange\”
Foreach($file in $files)
{
Write-Host “Attaching File :- ” $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList S:\sites\filechange$file
$msg.Attachments.Add($attachment)
}
$smtp.Send($msg)
$attachment.Dispose();
$msg.Dispose();
Copy-Item c:\sites$name C:\a$name } 

我检查这个脚本是否对我有用,如果首先更改文件的文件内容电子邮件日志文件然后将它们复制到目标 c:\a\ 还有你和那个文件更改为邮件附件