1

一段时间以来,我一直在使用以下备份脚本来为 MSSQL 数据库创建 .bacpac 文件。该脚本一般工作正常,但对于某些数据库失败。这些数据库与其他数据库没有太大不同,可能更大一些。由于这仅用于开发数据库,​​因此平均大小不大,bacpac 文件大小约为 200Mb。

奇怪的事情是脚本在从 PowerShell ISE 执行时成功运行,但在从命令行运行时失败。请注意,脚本仅对某些数据库失败,而对其他数据库有效。错误消息并没有真正的帮助:

警告:发生异常:使用“2”参数调用“ExportBacpac”的异常:“无法从数据库导出架构和数据。”

我们使用 MSSQL 2104,数据库可以毫无问题地从 MSSQL Studio 导出到备份。

剧本:

Param(
    # Database name to backup e.g 'MYDB'
    $databaseName,
    # Database connection string "server=server ip;Integrated Security = True;User ID=user;Password=pass"
    $connectionString,
    # Path to the directory where backup file should be created
    $backupDirectory
)
add-type -path "C:\Program Files (x86)\Microsoft SQL Server\120\DAC\bin\Microsoft.SqlServer.Dac.dll";

try {
    $dacService = new-object Microsoft.SqlServer.Dac.DacServices $connectionString
    # build backup filename
    $backupFileName  = $backupDirectory+"\"+$dataBaseName+[DateTime]::Now.ToString("yyyyMMdd-HHmmss")+".bacpac" 
    # perform backup
    $dacService.exportBacpac($backupFileName, $dataBaseName);
    Write-Output "Database backup file created $backupFileName"
} catch {
    Write-warning "Exception occurred: $_"
    throw "Database backup haven't been created, execution aborted."
}

有没有人遇到过这个问题?我知道 PowerShell 和 PowerShell ISE 有点不同,但我不明白为什么脚本执行会产生不同的结果。

[编辑]

尝试为 DacService 添加事件侦听器并打印输出以获取更多调试信息

 register-objectevent -in $dacService -eventname Message -source "msg" -action { out-host -in $Event.SourceArgs[1].Message.Message } | Out-Null

输出是

Dac Assembly loaded.
Extracting schema (Start)
Gathering database options
Gathering users
WARNING: Exception occurred: Exception calling "ExportBacpac" with "2" argument(s): "Could not export schema and data
from database."
Gathering roles
Gathering application roles
Gathering role memberships
Gathering filegroups
Gathering full-text catalogs
Gathering assemblies
Gathering certificates 
....
Processing Table '[dbo].[file_storage_entity]'. 99.74 % done.
Processing Table '[dbo].[file_storage_entity]'. 100.00 % done.
Exporting data (Failed)

[编辑 2]

作为一种解决方法,我创建了 C# 程序来做同样的事情。在任何环境下都能正常运行。该代码与 PowerShell 脚本中的代码几乎相同。

4

0 回答 0