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'. "
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
}
Here's how to do it:
# 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)
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();
###############################################################################################
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With