惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Cisco Talos Blog
Cisco Talos Blog
C
Check Point Blog
博客园_首页
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
S
Security @ Cisco Blogs
L
LINUX DO - 最新话题
博客园 - 司徒正美
P
Privacy International News Feed
G
Google Developers Blog
I
Intezer
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Scott Helme
Scott Helme
K
Kaspersky official blog
I
InfoQ
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Webroot Blog
Webroot Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
大猫的无限游戏
大猫的无限游戏
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
量子位
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
S
Security Affairs
Latest news
Latest news
人人都是产品经理
人人都是产品经理
C
CERT Recently Published Vulnerability Notes
S
Security Archives - TechRepublic
V
Visual Studio Blog
T
Troy Hunt's Blog
S
Secure Thoughts
F
Fortinet All Blogs
V
V2EX
The Register - Security
The Register - Security
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - ok_008

解决GitHub加载和下载慢问题 mysql命令行爱好者必备工具mycli What is a Back Order mysql中实现字符串分割sp_split Down Payment 和 Deposit的差异 Select逻辑顺序图 排名趋势公式 批量替换存储过程内容脚本sp_SqlReplace 生成建表脚本up_CreateTable Data Model for Certificate Implementation of Message Receiver Data Model for Message Receiver SQL SERVER 批量生成编号 修改hosts文件 PHP-问题处理验证码无法显示出来 PHP-问题处理Fatal error: Uncaught Error: Call to undefined function mb_strlen() - ok_008 PHP-问题处理Fatal error: Uncaught Error: Call to undefined function simplexml_load_file() - ok_008 10进制转33进制 PHP-生成缩略图和添加水印图-学习笔记 SQLServer地址搜索性能优化例子
批量备份数据库脚本(PowerShell版)
ok_008 · 2017-04-15 · via 博客园 - ok_008

开始

        昨天备份一个数据库拿来测试,发现备份后的文件非常大。后来去检查下使用的备份脚本,原来之前的备份脚本没有压缩功能。

        现把之前的备份脚本修改下,支持压缩备份,和支持仅复制备份(CopyOnly).

备份数据库(完整备份)脚本

   (注:开初编写这脚本的目的是能批量备份数据库,提高工作效率,后面提到的还原数据库脚本也是如此。)

<#=====================================================================#>
##备份数据库(完整备份)V2.0 Andy 2017-4-13 增加了设置压缩备份,和是否使用复制备份功能
##备份数据库(完整备份)V1.0 Andy
##
##

[string]$serverInstance="IP\InstanceName" 
[string]$userName="Login"
[string]$password="Password"
[string]$Path="\\xxx.xxx.xxx.xxx\xxxBackup"

[string]$DBList="dbname" #(选填)数据库列表,数据库之间使用','隔开,留空表示所有数据库
[bool]$CopyOnly=$true; #为 True,仅复制备份;否则不是仅复制备份,而是平常备份序列的一部分
[int32]$CompressionOption=1 #1 启动压缩  ,2 禁用压缩






[bool]$AddBackupTime= 1 #(选填) 备份文件名是否加备份时间,格式为:_yyyyMMddHHmmss

<#=====================================================================#>


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null

[string]$DBName=""
[datetime]$StartTime=Get-Date
$Path=$Path+$(If($($Path.Split("\"))[-1] -eq "" ){""} Else {"\"})

$ServerConnection =new-object "Microsoft.SqlServer.Management.Common.ServerConnection" $serverInstance,$userName, $password 


Clear-Host #清除控制台的内容

#--------------------------------------
#检查备份数据库清单
#--------------------------------------
Function CheckDB
{
    Param([String]$DBvar)
    
    Begin 
    {
        [Boolean]$CheckResult=$false
    }
    Process
    {
        If($DBList -eq "")
        {
            $CheckResult=$true
        }
        Else
        {
            Foreach($x In $DBList.Split(","))
            {
                If($x -eq $DBvar)
                {
                    $CheckResult=$true
                    Break
                }
            }
        }
    }
    End
    {
        Return $CheckResult
    }
}

#1. 连接实例
Try
{
    $ServerConnection.Connect()
}
Catch
{    
    Write-Host "无法连接到数据库实例:$serverInstance"   -ForegroundColor Red
}

#2. 判断备份路径是否正确
[bool]$PathExists=Test-Path $Path

if ($PathExists -eq $false)
{
    Write-Host "无效的路径:$Path"   -ForegroundColor Red
}

#3. 备份数据库
if ($ServerConnection.IsOpen -and $PathExists -eq $true)
{

    Try
    {
        $Server=new-object "Microsoft.SqlServer.Management.Smo.Server" $ServerConnection
        $Backup=new-object "Microsoft.SqlServer.Management.Smo.Backup"
        
        [string]$strDate =if($AddBackupTime -eq $true){Get-Date -Format "_yyyyMMddHHmmss"}else{""}
        
        $Backup.Action=[Microsoft.SqlServer.Management.SMO.BackupActionType]::Database
        $Backup.Incremental =$false
        $Backup.CompressionOption=$CompressionOption;
        $Backup.CopyOnly=$CopyOnly;  
        
        foreach ($DB in $Server.Databases | Select-Object -Property Name,IsSystemObject | Where-Object -FilterScript {$_.IsSystemObject -eq $false})
        {
            $DBName=$DB.Name
            if (CheckDB($DBName) -eq $true ) #判断$DBName是否在备份数据库列表中
            {                
                $Backup.Database =$DBName
                $Backup.Devices.Clear()
                $Backup.Devices.AddDevice($Path+$DBName+$strDate+".bak",[Microsoft.SqlServer.Management.Smo.DeviceType]::File)
            
                $Backup.SqlBackupAsync($Server) #异步处理备份
                Write-Host "正在备份 $DBName ... ..." -BackgroundColor Blue -ForegroundColor White
                
                $Backup.Wait() #等待备份完成才继续
                Write-Host "完成备份 $DBName .      " -BackgroundColor Green    
                
            }
        }

        
        [TimeSpan]$Times = (Get-Date) - $StartTime
        [String]$Str=if($Times.Hours -eq 0){""}else{$Times.Hours.ToString()+ " 小时 "}
        $Str+=if($Times.Minutes -eq 0){""}else{$Times.Minutes.ToString()+" 分钟 "}
        $Str+=if($Times.Seconds -eq 0){""}else{$Times.Seconds.ToString()+""}
        Write-Host "备份总耗时: $Str"
        
    }
    Catch
    {    
        Write-Error $_
        Write-Host "在备份 $DB 过程中发生错误."   -ForegroundColor Red
    }
    
}

调用例子

 压缩后备份文件只有1G多。

 还原数据库可以参考《PowerShell应用之-批量还原数据库(支持完整,差异,事务日志)