4

スクリプトを変数にロードするコードがあり、その変数を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
    }
4

3 に答える 3

5

方法は次のとおりです。

# 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)
于 2013-10-30T21:44:03.743 に答える
1

Invoke-SqlCmdコマンドレットを使用してみてください。このコマンドレットを使用すると、 SQLCMDユーティリティでサポートされている T-SQL コードまたはコマンドを実行できます。

Try{
    Invoke-SqlCmd `
    -Query $createScript `
    -ServerInstance $serverName `
    -Database $databaseName `
    -ErrorAction Stop `
    }
    Catch
    {
        [system.exception]
        $_.Exception | Out-File -Append -FilePath $outputFile
    }
于 2013-11-01T13:06:27.817 に答える