您可以在 Powershell 中使用 exit 关键字。这是一个例子
创建一个名为 sqlcmdexit.ps1 的脚本,其内容如下:
$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
}
调用脚本并观察现有代码:
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
我不知道有什么方法可以设置默认的 ExitCode。使用 start-process 你可以做类似的事情:
$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
}