SMO 使用 PowerShell 生成数据库脚本,因此它与从 Management Studio 手动创建脚本时的方式相同

SMO generate database script using PowerShell, so it was same way as when creating script manually from Management Studio

我需要使用 SMO 在代码中生成脚本,因此它与我使用 Management Studio 手动创建脚本完全相同。 IE。数据库 -> 任务 -> 生成脚本.. -> 选择架构和数据。

所以我想要这样的东西:

USE [master]
GO

CREATE DATABASE [MyDatabase]
CONTAINMENT = NONE
ON PRIMARY 
( NAME = N'MyDatabase', FILENAME = N'C:\Databases\Data\MyDatabase.mdf' , SIZE = 100KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON 
( NAME = N'MyDatabase_log', FILENAME = N'C:\Databases\Data\MyDatabase_log.ldf' , SIZE = 100KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [MyDatabase] SET COMPATIBILITY_LEVEL = 100
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
BEGIN
    EXEC [MyDatabase].[dbo].[sp_fulltext_database] @action = 'enable'
END
GO

ALTER DATABASE [MyDatabase] SET ANSI_NULL_DEFAULT OFF 
...
GO

/****** Object:  DatabaseRole [StoreRW]    Script Date: 22.02.2019 10:14:14 ******/
CREATE ROLE [StoreRW]
GO

...
GO

CREATE TABLE [dbo].[MyTabale1](
...

即结果应包含 CREATE DATABASE 语句。

但目前我没有成功。我有数据库架构和数据,但没有 CREATE DATABASE .

我正在使用此代码:

$My="$ms.Management.Smo" #
$s = new-object ("$My.Server") $DataSource

if ($s.Version -eq $null) { Throw "Can't find the instance $Datasource" }

$ver = $s.Version
echo " SQL Server version is $ver"
$db= $s.Databases[$Database]

if ($db.name -ne $Database) { Throw "Can't find the database '$Database' in $Datasource" };

$transfer = new-object ("$My.Transfer") $db

if ($transfer -eq $null) { Throw "Can't create transfer object" }

$transfer.Options.Default = $true;
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.ToFileOnly = $true # this only goes to the file

$transfer.Options.ExtendedProperties = $true;
$transfer.Options.IncludeDatabaseContext = $true;
$transfer.Options.WithDependencies = $true;
$transfer.Options.IncludeHeaders = $true;
$transfer.Options.SchemaQualify = $true;
$transfer.Options.DriAll = $true;

$transfer.Options.ScriptData = $true;
$transfer.Options.ScriptSchema = $true;
$transfer.Options.FileName = $BackupFile;
$tmp = $transfer.Options;
echo " Transfer options are: $tmp";
$transfer.EnumScriptTransfer();
echo "Scripting database '$dbName' to '$BackupFile' done"

我需要添加什么才能让 CREATE DATABASE 也加入其中?

分配 $db 后需要添加此行:

$db.script()

如果您希望将该脚本数据输出到文件,则只需添加以下内容:

$db.script() | out-file "c:\folder\create-db.sql"