`

SMO+PowerShell 实现SQLServer数据库的备份与还原

阅读更多

 最近有需求,需要用脚本/命令行的形式实现对数据库的备份与还原!尝试几遍,那个郁闷啊!网上的例子又少,大多又运行不了,很是让人无语,弄了几天,最后总算搞清楚了一些,资料也找到了合适的一些!不过这之中还是得自己琢磨着!幸好最终能够实现功能.

首先以下分为两种:

 

1) 一种是脚本(.sql)的生成.
2 )一种是数据库的备份与还原. 
 

首先贴出SQL生成的脚本:(PowerShell 脚本)

  1.   release_1.1.ps1

 

#clear screen(清屏)
cls

#以下是相关加载
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for backup
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null


$serverName=$(read-host "Server ('localhost' okay)")   #服务器localhost或远程IP
$serverConn=new-object Microsoft.SqlServer.Management.Common.ServerConnection #服务器连接
$serverConn.ServerInstance=$serverName #设置SQL实例
$serverConn.LoginSecure =$false  
$serverConn.Login = $(read-host "Login UserName")  #登录用户名
$serverConn.Password =$(read-host "Login PassWord") #登录密码(不过是明文显示的) 
$user_folder=$(read-host "Please choice a folder location to backup the database") #指定备份存放位置
$objectoption = $(read-host "All Objects = 0, Tables = 1, Table Triggers = 2, Views = 3, Functions = 4, Stored Procedures = 5")
#选择备份的对象 (All Object 、table、trigger、view、function、procedure)
$reg=$(read-host "('WildCard' okay)")  #通配符(要什么条件的对象)
#write-host $user_folder #输出备份位置(Debug)
#trap errors #出错日志记录
$errors =$user_folder+"\errors.txt"  #指定一个出错日志存放目录文件.
#write-host $errors     #输出日志路径(Debug)
trap
{

"______________________" | out-file $errors -append;
"ERROR SCRIPTING TABLES" | out-file $errors -append;
get-date | out-file $errors -append;
"ERROR: " + $_ | out-file $errors -append;
"`serverName = $serverName" | out-file $errors -append;
"`user_folder = $user_folder" | out-file $errors -append;
#throw "ERROR: See $errors"
}

#Checks to see if the supplied Directory is there and creates it if not. Inside a Process to allow a Pipe to use it.
#判断目录是否存在、创建
function MakeDirectory 
{
	param([string]$DirName)
	Process
	{
		if (!(Test-Path -path $DirName))
		{
		  New-Item $DirName -type directory | Out-Null
		}
	}
}

MakeDirectory ($user_folder) #创建用户备份目录
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($serverConn)   #server对象
#"==============The Database Server have some databases below:============="
#foreach($database in $srv.databases)
#{
#  write-host $database.Name
#}
#$db=$(read-host "Choice A database to backup")
#$dbName=$srv.databases[$db].Name
#write-host $dbName
#"==============You choice database have some tables below:============="
#foreach($table in $srv.databases[$db].tables)
#{
#  write-host $table.Name
#}
#$objectOption = $(read-host "All Objects = 0, Tables = 1, Table Triggers = 2, Views = 3, Functions = 4, Stored Procedures = 5")
#write-host $objectOption
#$wildcards=$(read-host "Wildcards okay")
#write-host $wildcards
#if($objectOption -eq 0)
#{
#   write-host "All Objects"
#}
$dbInput=$(read-host "Choice a database to backup")
$db=$srv.databases[$dbInput]
$dbName=$db.Name
write-host "Current Database:"$dbName

$scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
$scr.Server = $srv
$scrOptions = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
$scrOptions.AllowSystemObjects = $false
$scrOptions.IncludeDatabaseContext = $false
$scrOptions.IncludeIfNotExists = $false
$scrOptions.ClusteredIndexes = $true
$scrOptions.NoCollation = $true
$scrOptions.Default = $true
$scrOptions.DriAll = $true
$scrOptions.Indexes = $true
$scrOptions.NonClusteredIndexes = $true
$scrOptions.IncludeHeaders = $false
$scrOptions.ToFileOnly = $true
$scrOptions.Permissions = $true
$scrOptions.ScriptDataCompression = $true
$scrOptions.ScriptDrops = $false
$scrOptions.AppendToFile = $true  #是追加还是覆盖
#Set options for SMO.Scripter
$scr.Options = $scrOptions
$backupfolder=$user_folder+"\"+$dbName+"_backup"    #filefolder
remove-item $backupfolder\*     #删除之前的备份
#write-host $backupfolder(Debug)
$backupfile=$backupfolder+"\"+$dbName+".backup.sql"; #file
#write-host $backupfile(Debug)
">>>>>>>>>>>>Start backup"
$tables=$db.Tables | where {$_.IsSystemObject -eq $false} | where-object {$_.name -like $reg}

if ($objectoption -eq 0 -or $objectoption -eq 1)
{
	# script each table
	foreach ($table in $tables)
	{   
	    
		MakeDirectory ($backupfolder); #Check for folder, and create if needed
		$scrOptions.FileName = $backupfile;
		$scr.Options = $scrOptions;
		$scr.Script($table);
	}
}
if ($objectoption -eq 0 -or $objectoption -eq 2)
{
	# Script table triggers (go into tables then triggers)
	foreach ($table in $tables)
	{
		foreach ($trigger in $Table.Triggers | where {$_.IsSystemObject -eq $false})
		{
			MakeDirectory ($backupfolder); #Check for folder, and create if needed
		    $scrOptions.FileName = $backupfile;
			$scr.Options = $scrOptions;
			$scr.Script($trigger);
		}
	}
}
if ($objectoption -eq 0 -or $objectoption -eq 3)
{
	# script each view
	foreach ($view in $db.Views | where {$_.IsSystemObject -eq $false})
	{
		MakeDirectory ($backupfolder); #Check for folder, and create if needed
		$scrOptions.FileName = $backupfile;
		$scr.Options = $scrOptions;
		$scr.Script($view);
	}
}
if ($objectoption -eq 0 -or $objectoption -eq 4)
{
	# script each function
	foreach ($function in $db.UserDefinedFunctions | where {$_.IsSystemObject -eq $false})
	{
		MakeDirectory ($backupfolder); #Check for folder, and create if needed
		$scrOptions.FileName = $backupfile;
		$scr.Options = $scrOptions;
		$scr.Script($function);
	}
}
if ($objectoption -eq 0 -or $objectoption -eq 5)
{
	# script each stored procedure
	foreach ($procedure in $db.StoredProcedures | where {$_.IsSystemObject -eq $false})
	{
		MakeDirectory ($backupfolder); #Check for folder, and create if needed
		$scrOptions.FileName = $backupfile;
		$scr.Options = $scrOptions;
		$scr.Script($procedure);
	}
} 
">>>>>>>>>>>>Backup Complete"

2. 批处理 (run.bat):

   其中set-location "  "自己定义

 

cls
powershell -command "&{.\release_1.1.ps1 Club.Secretary}"
 

 

以下是备份与还原数据库的脚本(PowerShell 脚本)

   release_1.0.ps1

 

#============================================================
# Restore a Database using PowerShell and SQL Server SMO
# Restore to the same database, overwrite existing db
#============================================================

#clear screen
cls

#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for backup
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null


$serverName=$(read-host "Server ('localhost' okay)") 
$serverConn=new-object Microsoft.SqlServer.Management.Common.ServerConnection
$serverConn.ServerInstance=$serverName
$serverConn.LoginSecure =$false
$serverConn.Login = $(read-host "Login UserName") 
$serverConn.Password =$(read-host "Login PassWord")
#$database = $(read-host "Database"),
$user_folder=$(read-host "Please choice a folder location to backup the database")
#$objectoption = $(read-host "All Objects = 0, Tables = 1, Table Triggers = 2, Views = 3, Functions = 4, Stored Procedures = 5")
#write-host $user_folder
# trap errors
$errors =$user_folder+"\errors.txt"
#write-host $errors
trap
{

"______________________" | out-file $errors -append;
"ERROR SCRIPTING TABLES" | out-file $errors -append;
get-date | out-file $errors -append;
"ERROR: " + $_ | out-file $errors -append;
"`serverName = $serverName" | out-file $errors -append;
#"`userName = $serverConn.Login" | out-file $errors -append;
"`user_folder = $user_folder" | out-file $errors -append;
#"`$tables = $tables" | out-file $errors -append;
#"`$path = $path" | out-file $errors -append;
#"`$scripts = $scripts" | out-file $errors -append;
#throw "ERROR: See $errors"
}
#Checks to see if the supplied Directory is there and creates it if not. Inside a Process to allow a Pipe to use it.
function MakeDirectory 
{
	param([string]$DirName)
	Process
	{
		if (!(Test-Path -path $DirName))
		{
		  New-Item $DirName -type directory | Out-Null
		}
	}
}
MakeDirectory ($user_folder)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($serverConn)
"==============The Database Server have some databases below:============="
foreach($database in $srv.databases)
{
  write-host $database.Name
}
$db=$(read-host "Choice A database to backup")
$dbName=$srv.databases[$db].Name
write-host $dbName
"==============The Database Server have some tables below:============="
foreach($table in $srv.databases[$db].tables)
{
  write-host $table.Name
}


#$table=$(read-host "Choice A table to backup")


#write-host $user_folder"\"$dbName".bak"
$folder=$user_folder+"\"+$dbName+".bak"
#write-host $folder
$backupDevice = New-Object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($folder, "File")

#################  Backup  ###############
">>>>>>>>>>>>>>>>>>>>>>Start Backup..."
$smoBackup=New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
#2010.10.16 paulus: overwrite
$smoBackup.Initialize = $TRUE
#2010.10.16 paulus: no need for timestamp
#$smoBackup.Devices.AddDevice($backupDirectory + "\" + $dbName + "_" + $timestamp + ".bak", "File")

$smoBackup.Devices.Add($backupDevice)  #$smoBackup.Devices.AddDevice($user_folder+"\"+$dbName+".bak", "File");
$smoBackup.SqlBackup($srv)
">>>>>>>>>>>>>>>>>>>>>Backup Complete"

################  Start Restore #############
">>>>>>>>>>>>>>>>>>>>>>Start Restore..."
$smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")
$smoRestore.NoRecovery = $false;
$smoRestore.Partial = $false
$smoRestore.ReplaceDatabase = $true;
$smoRestore.Action = "Database"
$smoRestore.Devices.Add($backupDevice)
$RestoreName=$(read-host "What you want restore name")
$smoRestore.Database =$RestoreName

$smoRestore.SqlRestore($srv)

#plus: set owner to sa
#$db = New-Object Microsoft.SqlServer.Management.Smo.Database
#$db = $srv.Databases.Item($RestoreName) #$smoRestoreDetails.Rows[0]["DatabaseName"]
#$db.SetOwner("sa", $TRUE)
#"Done"

">>>>>>>>>>>>>>>>>>>>>>Restore Complete"
 


同时提供以下资料可供参考:

 

http://www.simple-talk.com/sql/sql-tools/using-powershell-to-generate-table-creation-scripts/

利用 PowerShell 做 SQL 數據庫備份:

http://paulusyeung.wordpress.com/2010/10/17/%E5%88%A9%E7%94%A8-powershell-%E5%81%9A-sql-%E6%95%B8%E6%93%9A%E5%BA%AB%E5%82%99%E4%BB%BD/

 

利用 PowerShell 自動 Restore 數據庫:

http://paulusyeung.wordpress.com/2010/10/17/%E5%88%A9%E7%94%A8-powershell-%E8%87%AA%E5%8B%95-restore-%E6%95%B8%E6%93%9A%E5%BA%AB/

 

SMO 方法、属性速查:

 

http://msdn.microsoft.com/zh-cn/library/ms162169.aspx

 

 

 

0
1
分享到:
评论

相关推荐

    c# asp.net实现sql server数据库备份

    总之,使用C#和ASP.NET实现SQL Server数据库备份,主要涉及SMO库的使用,通过编写代码来配置备份类型、设备和选项,然后调用SqlBackup方法执行备份。在实际应用中,还需要考虑错误处理、日志记录、备份策略规划等...

    SQL Server数据库备份与恢复(C#代码示例)

    C#结合SQL Server的API,如SqlClient和Smo,可以方便地进行数据库的备份和恢复操作。 首先,让我们了解SQL Server数据库备份的基本概念。数据库备份是为了防止数据丢失,它将数据库的当前状态保存到一个或多个文件...

    Sqlserver数据库备份

    C#作为.NET框架的一部分,可以与SQL Server进行交互,实现自动化备份。要使用C#进行SQL Server数据库备份,你需要使用`System.Data.SqlClient`命名空间中的`SqlConnection`, `SqlCommand`和`SqlBackup`类。以下是一...

    sql2005数据库备份还原工具

    3. **备份操作**:调用SQL Server的T-SQL命令(如`BACKUP DATABASE`)或使用SQL Server Management Objects (SMO) API进行备份。 4. **文件I/O**:处理备份文件的保存和读取,包括文件路径的选择和验证。 5. **还原...

    还原SQL Server数据库

    在C#编程中,我们可以利用SQL Server Management Objects (SMO) 库来实现对SQL Server数据库的自动化操作,包括备份和还原。以下是一段C#代码示例,展示了如何执行数据库的完整备份: ```csharp using Microsoft....

    VB逻辑备份oracle、sqlserver数据库

    本文将深入探讨如何使用VB(Visual Basic)编写逻辑备份程序来实现Oracle和SQL Server数据库的备份。 首先,理解备份策略至关重要。在描述中提到的备份策略是一种常见的滚动备份策略,也被称为“覆盖式”或“逐日...

    sql server的备份与还原

    SQL Server的备份与还原是数据库管理中的核心操作,对于数据安全和业务连续性至关重要。在VB.NET编程环境中,我们可以利用Microsoft SQL Server Management Objects (SMO)库来执行这些任务。以下将详细介绍SQL ...

    SQL SERVER数据库备份恢复

    然而,需要注意的是,SQLDMO已被SMO(SQL Server Management Objects)取代,因此在最新的SQL Server版本中,推荐使用SMO进行数据库管理。 使用该组件进行备份,你需要指定要备份的数据库,选择合适的备份类型,...

    c#备份sqlserver数据库.zip

    本文将深入探讨如何利用C#语言来实现SQL Server数据库的备份操作。 首先,我们需要理解C#中的ADO.NET,这是一个用于与数据库交互的框架。通过ADO.NET,我们可以使用SqlConnection类建立到SQL Server的连接,Sql...

    c#写的sql Server数据库自动备份程序

    总之,这个程序将C#编程技能与数据库管理知识相结合,通过编写一个能够自动执行备份任务的应用程序,实现数据库的安全性与可靠性维护。开发者希望获取反馈,意味着这个程序很可能是一个学习示例,用于提高编程水平或...

    sql server sqldmo_x86_x64(C#数据库备份还原很好用的dll)

    sql server sqldmo_x86_x64,C#数据库备份还原很好用的.dll,里面有使用方法,引用Interop.SQLDMO.dll后的注意事项。 SQLDMO.dll是个好东西,ASP.NET利用它可以实现在线备份、还原数据库等各种功能。近日有客户...

    C#SQLServer数据库备份

    本文将深入探讨如何使用C#编程语言与SQL Server数据库进行交互,实现数据库的备份功能。 首先,C#是一种广泛用于开发Windows应用程序的面向对象的编程语言,由微软公司开发并推广。它具有丰富的类库,易于学习,且...

    SqlServer备份源码

    "SqlServer备份源码"指的是用于自动执行SQL Server数据库备份的编程代码,这通常涉及到SQL Server Management Objects (SMO) 或 Transact-SQL (T-SQL) 脚本。下面我们将深入探讨SQL Server备份的相关知识点。 1. **...

    C#带进度条数据库备份

    通过建立连接,执行SQL语句(如BACKUP DATABASE命令),可以实现数据库的备份操作。 3. **带进度条显示**: 要在用户界面中显示进度条,可以使用Windows Forms或WPF中的ProgressBar控件。在执行备份操作时,需要...

    pb在SQL2000中的数据备份和还原原代码

    总之,PB在SQL Server 2000中的数据备份和还原涉及到了数据库管理的核心技能,开发者需要理解SQL Server的备份和还原机制,以及如何在PB环境中调用这些功能。通过合理的设计和编程,可以在PB中实现高效、可靠的数据...

    sqlserver2008远程备份、还原和压缩日志文件

    本篇将深入探讨如何在VS2010环境下,通过编程方式实现SQL Server 2008的远程备份、还原以及日志文件的压缩。 首先,我们来讨论SQL Server 2008的远程备份。在VS2010中,可以使用SQL Server Management Objects (SMO...

    Sqlserver数据库迁移

    在"Sqlserver数据库迁移"这个小项目中,我们主要关注的是如何将现有的SQL Server数据库从一个环境迁移到另一个环境,这可能涉及到数据的备份、恢复、复制以及同步等多个环节。以下是一些关于此话题的关键知识点: 1...

    PowerShell for SQL Server Essentials

    【PowerShell for SQL Server Essentials】是SQL Server管理与自动化的核心工具之一,尤其对于大型和复杂的数据库环境,PowerShell提供了一种高效、灵活的方式来执行任务。本文将深入探讨PowerShell在SQL Server中的...

    C#实现数据库前台备份还原代码,只有备份和还原两个功能

    本示例涉及的主题是如何使用C#来实现数据库的前台备份和还原功能。这两个功能在数据库管理中至关重要,因为它们允许在出现问题时恢复数据或者在迁移系统时保持数据一致性。 首先,我们需要了解SQL Server提供的API...

Global site tag (gtag.js) - Google Analytics