Powershell Invoke-Sqlcmd的错误检测并不总是有效?

通过执行位于文件夹中的查询列表来更新数据库.

我需要能够检测到任何错误,这些错误也会导致sql Server Management Studio中的“Query completed with errors”.

以下工作检测“无效对象”错误

PS sqlSERVER:\> $ErrorActionPreference
Stop
PS sqlSERVER:\> $Error.Clear()
PS sqlSERVER:\> $Error
PS sqlSERVER:\> Invoke-sqlcmd -ServerInstance .\sqlEXPRESS -Database Test -Query "select * from doesnotexist" -ErrorAction SilentlyContinue
PS sqlSERVER:\> $Error.Exception
Invalid object name 'doesnotexist'.
PS sqlSERVER:\>

对select 1/0执行相同操作不起作用:

PS sqlSERVER:\> $ErrorActionPreference
Stop
PS sqlSERVER:\> $Error.Clear()
PS sqlSERVER:\> $Error
PS sqlSERVER:\> Invoke-sqlcmd -ServerInstance .\sqlEXPRESS -Database Test -Query "select 1/0" -ErrorAction SilentlyContinue
PS sqlSERVER:\> $Error.Exception
PS sqlSERVER:\>

我希望这会导致像SSMS一样出现“遇到零除错误错误.

没有检测到这个特定的错误让我想知道其他错误是否也会被检测不到.

知道为什么会发生这种情况以及如何确保检测到所有错误

UPDATE

事实证明我在我安装的服务器上没有可用的Invoke-sqlcmd,所以第二个想到我必须使用sqlcmd.exe.

我认为这对我有用:

$tempfile = [io.path]::GetTempFileName()
$cmd = [string]::Format("sqlcmd -S {0} -U {1} -P {2} -d {3} -i {4} -b > $tempfile",$g_connectionstring."Data Source",$g_connectionstring."User ID",$g_connectionstring."Password",$g_connectionstring."Initial Catalog",$path)
Invoke-Expression -Command $cmd
if ($LASTEXITCODE)
{
    $err = Get-Content $tempfile | Out-String
    Corax-Message "sql" "Error" $err
    exit
}
Remove-Item $tempfile

解决方法

无论ErrorAction设置如何,invoke-sqlcmd cmdlet在sql Server 2008,2008和2012版本的cmdlet中都存在一个错误,其中除以0之类的T-sql错误不会导致错误.我在此处记录了一个连接项,您可以在此处查看详细信息:

https://connect.microsoft.com/SQLServer/feedback/details/779320/invoke-sqlcmd-does-not-return-t-sql-errors

注意:该问题已在sql 2014中修复,但似乎未出现或将要为以前的版本提供修复.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...