SQL Server 2012 Powershell 脚本以生成具有架构和数据的数据库

Har*_*ald 4 sql-server powershell scripting sql-server-2012

使用 Sql Server 2012,有人可以向我展示一个简单的 powershell 3 脚本来生成我的整个数据库(架构和数据)吗?

我试过这个:

$Filepath='d:\b\t' # local directory to save build-scripts to
$DataSource='HH' # server name and instance
$Database='HMovies'# the database to copy from
# set "Option Explicit" to catch subtle errors
set-psdebug -strict
$ErrorActionPreference = "stop" # you can opt to stagger on, bleeding, if an error occurs
# Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries
$ms='Microsoft.SqlServer'
$v = [System.Reflection.Assembly]::LoadWithPartialName( "$ms.SMO")
if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {
[System.Reflection.Assembly]::LoadWithPartialName("$ms.SMOExtended") | out-null
   }
$My="$ms.Management.Smo" #
$s = new-object ("$My.Server") $DataSource
if ($s.Version -eq  $null ){Throw "Can't find the instance $Datasource"}
$db= $s.Databases[$Database]
if ($db.name -ne $Database){Throw "Can't find the database '$Database' in $Datasource"};
$transfer = new-object ("$My.Transfer") $db
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.ToFileOnly = $true # this only goes to the file
$transfer.Options.ScriptData = $true;
$transfer.Options.Filename = "$($FilePath)\$($Database)_Build.sql";
$transfer.ScriptTransfer()
"All done"
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误

Exception calling "ScriptTransfer" with "0" argument(s): "This method does not support scripting data."
Run Code Online (Sandbox Code Playgroud)

如果我禁用 ScriptData 选项,它会起作用,但当然我只会得到模式。我已经用谷歌搜索了几个小时,但我找不到一个简单的脚本(没有存储过程的花里胡哨等)来执行这个简单的任务。

我的时间不多了。请帮忙。

Hea*_*ing 5

我想使用 Powershell 编写一个小型数据库的脚本,以便我可以跟踪 git 中的更改。我找到了您使用的相同脚本作为起点: Automated Script Generation with Powershell and SMO

您可以在此处找到 ScriptingOptions 类的所有选项:ScriptingOptions Class

由于现在已弃用的ScriptTransfer方法,您会收到错误消息。

替换这一行

$transfer.ScriptTransfer()
Run Code Online (Sandbox Code Playgroud)

有了这个

$transfer.EnumScriptTransfer()
Run Code Online (Sandbox Code Playgroud)

并且您的脚本应该运行。