Erreur lors de l'exécution du script SQL via SMO dans PowerShell

J'ai du code qui charge un script dans une variable, puis je passe la variable à un object SMO . Je reçois l'exception suivante:

Exception appelant "ExecuteWithResults" avec "1" argument (s): "Exécuter avec les résultats a échoué pour la database 'Russell_Test'."

  • $ serverName est le nom du server.
  • $ databaseName est le nom de la database.
  • $ createScript est le script qui a été lu.

Comment puis-je résoudre ce problème?

Voici la partie pertinente du 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 } 

Voici comment le faire:

 # If we cast $Content as a [Ssortingng], 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 SsortingngCollection, not a List or Array $Batch = New-Object -TypeName:Collections.Specialized.SsortingngCollection $Batch.AddRange($Content) $result = $Database.ExecuteWithResults($Batch) 

Merci pour l'aide. En fin de count l'option SMO ne fonctionnerait pas alors j'ai fait cette solution:

 # Deploy table update scripts $createScript = Get-Content $scriptFile.FullName | Out-Ssortingng ################# 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(); ############################################################################################### 

Essayez d'utiliser la cmdlet Invoke-SqlCmd . Cette cmdlet vous permet d'exécuter du code T-SQL ou des commands sockets en charge par l'utilitaire SQLCMD .

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