木木的大象

导航

PowerShell文件自动备份

PowerShell是系统管理员的好工具,特别是它可以调用.Net的类库能帮助系统管理员实现以前很繁复的工作.以下是一个自动备份的ps脚本,呵呵,可以省去不少钱和时间。

 

#=======================================================================================================
#
文件服务器自动隔日备份。邮件通知相关人员。
#
Copy Right ZYQ
#
日期:2010-6-29
#
最后修改日期:2010-10-21
#
=======================================================================================================
set-ExecutionPolicy Bypass -Force
$dedir="这里是存放备份文件夹的路径"
$LogDetail="这里是存放备份日志文件文件夹的路径"
$sourcedir="这里是要备份的文件夹的路径"
$lastdate=(Get-Date).AddDays(-1).Date
if( [System.Diagnostics.EventLog]::SourceExists("日志文件名称"-eq 0)
{
    [System.Diagnostics.EventLog]::CreateEventSource("日志文件名称","日志文件名称显示名称")
}
$log=Get-EventLog -List | Where-Object{$_.Log -eq "日志文件名称显示名称"}
$log.Source="日志文件名称"
Set-Location $sourcedir
$log.WriteEntry($lastdate.ToShortDateString()+"备份开始","SuccessAudit")
$i=0
$DetailRecord=New-Object System.Text.StringBuilder
[void] $DetailRecord.AppendLine([System.String]::Concat($lastdate.ToShortDateString(),"文件备份明细记录"))
#以下的$file是System.IO.FileSystemInfo对象
#
foreach( $file in Get-ChildItem -Recurse | Where-Object{(($_.LastWriteTime -ge $lastdate) -or ($_.LastWriteTime -lt $_.CreationTime)) -and ($_.Mode -eq '-a---')})
foreach$file in Get-ChildItem -Recurse | Where-Object{(($_.LastWriteTime -ge $lastdate)) -and ($_.Mode -eq '-a---')})
{
    #以下的$file是System.IO.filesinfo对象
    $newfold=[string]($file.DirectoryName).Replace($sourcedir,$dedir)
    if ([system.IO.Directory]::Exists($newfold-eq 0)
    {
        md $newfold
    }
    Copy-Item $file.FullName -Destination $newfold 
    $i++
    $msg="{0}被修改或创建的文件{1}已备份到{2}" -f $lastdate.ToShortDateString(),$file.FullName,$newfold
    [void] $DetailRecord.AppendLine($msg)
    #[System.Diagnostics.Debug]::Print($msg)
    $newfold=""
    $msg=""
}
#保存到文件
$LogDetail=$LogDetail +(Get-Date).Date.ToShortDateString().Replace("/","").Replace("-","")+".log"
if([System.IO.File]::Exists($LogDetail-gt 0)
{
    [System.IO.File]::Delete($LogDetail)
}
[System.IO.File]::AppendAllText($LogDetail,$DetailRecord.ToString()) 
#发送Email给xxx
$smtp=New-Object System.Net.Mail.SmtpClient 
$smtp.Host="这里是发送邮件服务器"
$Credential=New-Object System.Net.NetworkCredential 
$Credential.UserName="这里是发送邮件的用户名"
$Credential.Password="这里是发送邮件用户密码"
$Credential.Domain="这里是发送邮件用户所在的域名称"
$smtp.Credentials=$Credential
[void] $smtp.Send("发送者邮件地址","接收者邮件地址",[System.String]::Concat($lastdate.ToShortDateString(),"自动备份明细(",$i,")"),$DetailRecord.ToString())

#写入日志
$log.WriteEntry([System.String]::Concat($lastdate.ToShortDateString(),"备份结束。",$i,"个文件被复制到",$dedir,"。明细请看",$LogDetail,""),"SuccessAudit")
Exit

使用下来,对100G的文件夹进行操作用时3.5分钟. 

转载请注明:http://www.cnblogs.com/RZYQ/archive/2011/12/30/2308043.html

posted on 2011-12-30 21:48  木木的大象  阅读(1507)  评论(0编辑  收藏  举报