捕获 VBS objshell.Run 错误

Capture VBS objshell.Run error

我有下面的 VBS 位,它通过 SQLCMD 调用并运行 *.sql 查询。

如何改进错误检查?如果我删除 *.sql 文件,它认为它已经成功完成,即使它不可能有。

Writelog "Attempting to run *.sql"
err = objshell.Run ("cmd /c sqlcmd -U sa -P Password -i c:\temp\abc.sql",1,FALSE)
If err <> 0 Then
    WriteLog "Error running SQL = " & err & "(" & err.description & ")"
Else
    WriteLog "Successfully run SQL"
End If

正如@Noodles 在对您问题的评论中指出的那样,您需要将 Run 方法 (bWaitOnReturn) 的第三个参数设置为 True 以便您的 VBScript 等待要完成的外部命令。

然而,仅此还不够。您还需要 运行 sqlcmd 和附加参数 -b 以使其 return 在出现错误时成为非零退出代码:

-b

Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity level greater than 10; otherwise, the value returned is 0. If the -V option has been set in addition to -b, sqlcmd will not report an error if the severity level is lower than the values set using -V. Command prompt batch files can test the value of ERRORLEVEL and handle the error appropriately. sqlcmd does not report errors for severity level 10 (informational messages).

If the sqlcmd script contains an incorrect comment, syntax error, or is missing a scripting variable, ERRORLEVEL returned is 1.

而且您不需要 cmd /c,因为您的外部命令不使用任何 CMD 内置功能(如内部命令、管道或重定向)。

此外,不要使用 err 作为变量名。 VBScript 有一个内部全局对象 Err 用于提供 运行 时间错误信息,当发生 运行 时间错误时会自动填充。尝试为其赋值应该会自行引发错误。

将您的代码更改为如下内容:

rc = objshell.Run("sqlcmd -b -U sa -P Password -i c:\temp\abc.sql", 1, True)
If rc <> 0 Then
    WriteLog "Error running SQL = " & rc
Else
    WriteLog "Successfully run SQL"
End If