2012-07-25 2 views
1

PowerShell에서 sqlcmd를 호출하여 T-SQL 스크립트를 실행합니다. 현재 제약 조건을 위반하는 데 사용되는 데이터로 인해 오류가 발생하면 스크립트를 종료하기 위해 ": On Error exit"를 사용합니다. $ SqlcmdProcess.ExitCode 1을 감지하는 PowerShell에서 처리합니다.PowerShell에서 연결/데이터 문제와 관련하여 다른 sqlcmd 종료 코드 사용

그러나 if 데이터베이스와의 연결 문제가 있습니다. sqlcmd 또한 1의 ExitCode를 제공합니다. 설정 방법은 다음과 같습니다. On Error ExitCode를 1 이외의 값으로 설정 하시겠습니까? 같은 것을 사용하여 알고 있어요 : Exit (SELECT 2)이 작업을 수행 할 수 있지만 차라리 여전히 사용하고 싶습니다 : 오류 때문에 스크립트를 다시 작성할 필요가 없습니다.

답변

0

Powershell에서 exit 키워드를 사용할 수 있습니다. 여기에 예를

의 다음과 같은 뭔가 sqlcmdexit.ps1라는 스크립트 작성 :

C:\Users\Public\bin>.\sqlcmdExit.ps1 
Sqlcmd: Error: Microsoft SQL Server Native Client 10.0 : A network-related or instance-specific error has occurred while 
establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and i 
f SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.. 
Sqlcmd: Error: Microsoft SQL Server Native Client 10.0 : Login timeout expired. 

C:\Users\Public\bin>$LASTEXITCODE 
99 

내가 어떤 길을 잘 모르는 것 같아요 :

$result = sqlcmd -S"missing" -d master -Q "select @@servername" 
if ($result[1] -like "*Error Locating Server/Instance Specified*" -or $result[1] -like "*Could not open a connection to SQL Server*") { 
    exit 99 
} 

전화 스크립트를 관찰 코드 존재 기본 ExitCode를 설정합니다. 시작 프로세스를 사용하면 다음과 비슷한 결과를 얻을 수 있습니다.

$tempFile = [io.path]::GetTempFileName() 
$exitCode = (Start-Process -FilePath "sqlcmd.exe" -ArgumentList @" 
-S"missing" -d master -Q "select @@servername" 
"@ -Wait -NoNewWindow -RedirectStandardOutput $tempFile -Passthru).ExitCode 

if ($exitCode -eq 1) { 
    $result = get-content $tempfile 
    if ($result[1] -like "*Error Locating Server/Instance Specified*" -or $result[1] -like "*Could not open a connection to SQL Server*") { 
     remove-item $tempFile 
     Exit 99 
    } 
} 
else { 
    remove-item $tempfile 
    Exit $exitCode 
} 
+0

감사합니다. 이것은 매우 유용하며 다른 유형의 오류를 구분할 수 있습니다. 그러나 변수에 sqlcmd 결과를 캡처하려면 Start-Process에서 sqlcmd를 호출하는 중 약간의 재 작성이 필요합니다 (죄송합니다.). 프로세스 객체로 비슷한 일을 할 수있는 방법이 있는지 알고 있습니까? 내가 아는 한 ExitCode 및 ExitTime 속성 만 있습니다. 또는 T-SQL에서 오류가 발생하면 기본 ExitCode를 설정하는 방법이 있습니까? – user1551288

+0

수정 사항보기 - 시작 프로세스 예제 추가. –

+0

감사! 내가 정확히 그걸 할 거라 확신하지는 않지만, 내가 필요한 모든 것을 나에게 주었다고 생각한다. 건배. – user1551288