在PowerShell中通过SMO执行SQL脚本时出错



我有一些代码将脚本加载到变量,然后将变量传递给SMO对象。我得到以下异常:

使用"1"参数调用"ExecuteWithResults"的异常:"执行 数据库"Russell_Test"的结果失败。 "

  • $serverName是服务器名称。
  • $databaseName是数据库名称。
  • $createScript是读取的脚本。

如何解决此问题?

下面是代码的相关部分。

# Load Smo and referenced assemblies.
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.ConnectionInfo');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.Sdk.Sfc');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended');
    Try{
        $server = New-Object Microsoft.SqlServer.Management.Smo.Server $serverName;
        $db = $server.Databases.Item($databaseName);
        $result = $db.ExecuteWithResults($createScript);
        $result | Out-File -Append -FilePath $outputFile;
    }
    Catch
    {
        [system.exception]
        $_.Exception | Out-File -Append -FilePath $outputFile
    }
操作

方法如下:

# If we cast $Content as a [String], all the newlines are lost
# If we don't cast it, it becomes an array and batching breaks
$Content = (Get-Content $SqlScript) -join [Environment]::NewLine
# When using GO, we must set it up as a StringCollection, not a List or Array
$Batch = New-Object -TypeName:Collections.Specialized.StringCollection
$Batch.AddRange($Content)
$result = $Database.ExecuteWithResults($Batch)

感谢您的帮助。 最终SMO选项不起作用,所以我做了这个解决方案:

# Deploy table update scripts
$createScript = Get-Content $scriptFile.FullName | Out-String
################# Script execution to capture errors/messages/warnings ##################
        $createScriptList = [regex]::Split($createScript, 'bGO')
        $cn2 = new-object system.data.SqlClient.SQLConnection("Data Source=$serverName;Integrated Security=SSPI;Initial Catalog=$databaseName;Connection Timeout=600;Max Pool Size=10");
        $cn2.Open();
        foreach ($cSL in $createScriptList)
            {
                Try{
                $cmd = new-object system.data.sqlclient.sqlcommand($cSL, $cn2);
                $cmd.ExecuteScalar() | Out-File -Append -FilePath $outputFile;
                }
                Catch
                {
                    [system.exception]
                    $_.Exception | Out-File -Append -FilePath $outputFile
                }
            }
        $cn2.Close();
###############################################################################################

尝试使用 Invoke-SqlCmd cmdlet。此 cmdlet 允许你运行 SQLCMD 实用工具支持的 T-SQL 代码或命令。

Try{
    Invoke-SqlCmd `
    -Query $createScript `
    -ServerInstance $serverName `
    -Database $databaseName `
    -ErrorAction Stop `
    }
    Catch
    {
        [system.exception]
        $_.Exception | Out-File -Append -FilePath $outputFile
    }

最新更新