Search code examples
sql-serverpowershellsmo

Error executing SQL script via SMO in PowerShell


I have some code that loads a script to a variable, and then I pass the variable to an SMO object. I get the following exception:

Exception calling "ExecuteWithResults" with "1" argument(s): "Execute with results failed for Database 'Russell_Test'. "

  • $serverName is the server name.
  • $databaseName is the database name.
  • $createScript is the script that was read.

How can I fix this problem?

Below is the relevant portion of the code.

# 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
    }

Solution

  • Thanks for the help. Ultimately the SMO option would not work so I did this solution:

    # 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();
    ###############################################################################################