在Power shell中复制打开的文件

时间:2015-06-26 03:12:04

标签: email powershell backup locked-files

我是PowerShell的新手,我已经设法谷歌一起获取以下PowerShell脚本:

#System Variable for backup Procedure

 $date = Get-Date -Format d.MMMM.yyyy
 New-PSDrive -Name "Backup" -PSProvider Filesystem -Root "\\server>\<path>"
 $source = "\\server>\<path>"
 $destination = "\\<server>\<path>\$date"
 $path = test-Path $destination

电子邮件变量

 $smtp = "smudmug.mug"
 $from = "James Clegg <email@email.com>"
 $to = "James Clegg <email@email.com>"
 $body = "Hi All, </br></br> Please find the back up log File for <Server>      attached.</br></br> Back up complete on $date</br></br>Kind Regards,</br></br> James"
 $subject = "Backup of <Server> is Complete $date"

备份流程已启动

if ($path -eq $true) {
write-Host "Folder Already exists"
Remove-PSDrive "Backup"  
} elseif ($path -eq $false) {
        cd backup:\
        copy-Item -Recurse $source -passthru -Destination $destination
        $backup_log = Dir -Recurse $destination | out-File      "$destination\backup_log.txt"
        $attachment = "$destination\backup_log.txt"
        #Send an Email to User 
        send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject        $subject -Attachments $attachment -Body $body -BodyAsHtml
        write-host "Backup Successful"
        cd c:\

     Remove-PSDrive "Backup"  
     }

   cmd /c pause | out-null

有人可以帮助我,我需要添加哪些内容才能复制使用中的文件。

亲切的问候,

詹姆斯

1 个答案:

答案 0 :(得分:1)

Copying files that are open in another an application is not trivial. The problem is that even if you could copy the file, there is no guarantee that the file is in usable a state. All but the most simple text files are easily corrupted. Consider the following scenario:

   user           backup
    |                |
 (saves doc)         |
    |                |
(write n chars)      |
    |             (read file)   
(write m chars)   (write copy)
    |                |

What is the desired outcome? From user's point of view, the document should contain either state before save or before it. The actual outcome, only some saved changes, is hardly correct. If the file is more complex a structure, like a spreadsheet, the result can be corrupted beyond repair.

In order to work around this kind of concurrency issue, ther are open file agents. In Windows, there is a built-in VSS (Volume Shadow Copy Service), 3rd party products exist too. The idea is to watch the file for activity and make a consistent copy when all changes are flushed to the disk. This requires co-operation from the application too. For a detailed discussion about VSS, read Technet article. Your best bet is to use an existing backup solution that already has tackled the issue.