无法使用Powershell创建SQL脚本传输

时间:2019-02-08 13:32:35

标签: sql-server powershell smo

尝试创建数据库脚本时出现下一个错误:

  

使用“ 0”参数调用“ EnumScriptTransfer”的异常:“脚本   转移失败。 “位于C:\ temp \ Test.ps1:126 char:5   + $ transfer.EnumScriptTransfer();   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:未指定:(:) [],ParentContainsErrorRecordException       + FullyQualifiedErrorId:FailedOperationException

同一脚本在另一台计算机上正常工作。因此,我认为原因是在SQL Server版本或权利中。 有什么想法吗?

代码:

echo "Scripting database $dbname .."    
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")
$ver = (($v.FullName.Split(','))[1].Split('='))[1];
$vtmp=$ver.Split('.')[0];
echo " SMO version is $ver"
if ($vtmp -ge 9) {
            echo " Running SQL 2008, load the SMOExtended .."
            [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"}
$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.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 = $BackupFile;
$tmp = $transfer.Options
echo " Transfer options are: $tmp"
echo "    $transfer"
$transfer.EnumScriptTransfer();

输出:

Scripting database MyDbName ..
 SMO version is 14.0.0.0
 SQL Server version is 14.0.1000
 Transfer options are: ScriptingOptions: ScriptBatchTerminator, ToFileOnly, SchemaQualify, WithDependencies, AllowSystem
Objects, AgentJobId, NoVardecimal, ScriptSchema, ScriptData, ScriptDataCompression, PrimaryObject
    Microsoft.SqlServer.Management.Smo.Transfer
Exception calling "EnumScriptTransfer" with "0" argument(s): "Script transfer failed. "
At C:\temp\Test.ps1:126 char:5
+     $transfer.EnumScriptTransfer();
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : FailedOperationException

试图添加try-catch块,但这不起作用。不知道为什么:

Try
{
 $transfer.EnumScriptTransfer();
}
Catch
{
 $msg = $_.Exception.Message;
 $innerMsg = $_.Exception.InnerException.Message;
echo $msg
echo $innerMsg 
throw;
}

0 个答案:

没有答案