2013-10-30 9 views
4

스크립트에 변수를로드 한 다음이 변수를 SMO 개체에 전달합니다. "1"인수 (들) "ExecuteWithResults"를 호출PowerShell에서 SMO를 통해 SQL 스크립트를 실행하는 중 오류가 발생했습니다.

예외 : 나는 다음과 같은 예외 얻을. "결과는 데이터베이스에 대한 '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 
    } 
+0

변수 $ createScript의 내용을 표시 할 수 있습니까? 여기 –

+0

이 읽을 데이터베이스 스크립트 코드입니다 : 이 테이블 scripttest (A VARCHAR (1)) GO'이에서를 읽고 실제 코드를 만들 를 GO '사용 Russell_Test입니다 :'$ createScript = GET-내용 $ scriptFile . 전체 이름 | Out-String' – Russ960

+1

이 간단한 CREATE 문을 사용해보십시오 : create table scripttest (VARCHAR (a)) –

답변

2

도움 주셔서 감사합니다. 궁극적으로 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(); 
############################################################################################### 
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) 
1

시도가 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 
    } 
+0

지난 연구를 기반으로 모든 오류를 포착 할 수 있을지 확신하지 못합니다. 스크립트가 시작된 모든 환경에서 sqlps 모듈을로드하는 데 문제가 있으므로 Invoke-SqlCmd를 사용하는 것은 아무런 의미가 없습니다. – Russ960

+0

-ErrorAction Stop 매개 변수는 오류를 잡는 데 도움이됩니다. 답변이 업데이트되었습니다. –