问题描述
我试图从批处理文件中运行postgres查询。但是,到目前为止,我无法检测到命令何时失败。以下是我到目前为止所尝试的内容:$ p $ $ $ $ c $ @FOR / F %% A IN('PSQL -U userName -d dbName -t -cSELECT * FROM nonExistantTable2 ^> ^& 1')DO @(
ECHO!ERRORLEVEL!
)
pre>
我也尝试了以下内容:
$ b $ 1在sql命令之前添加CALL 这个实例中的 cmd 实例和 errorlevel 不会被导出到 do 子句。
在纯批处理中更好的方法是:
类似于
> %tempFile%2& 1(
PSQL -U userName -d dbName -t -cSELECT * FROM nonExistantTable
)
如果不是errorlevel 1(
for / fusebackq delims =%% g in(%tempFile%)do(
echo %% g
)
)else(
echo ERRORLEVEL:%errorlevel %
)
del / q%tempFile%
I am attempting to run a postgres query from within a batch file. However, I have thus far been unable to detect when the command fails. The following is what I have tried thus far:
@FOR /F %%A IN ('PSQL -U userName -d dbName -t -c "SELECT * FROM nonExistantTable" 2^>^&1') DO @( ECHO !ERRORLEVEL! )
I have also tried the following:
1) Adding "CALL" prior to the sql command (CALL PSQL -U ...)
2) Adding "-v ON_ERROR_STOP=1" to the sql command, both with and without the "CALL" command (PSQL -U ... -v ON_ERROR_STOP=1)
However, the value of ERRORLEVEL is always coming out as zero. Does anyone know how to detect an error in a call to PSQL using batch? Specifically, the error I am getting is that the table doesn't exist. Thanks.
The for /f executes the command in a separate cmd instance and the errorlevel from this instance is not exported to the code inside to do clause.
The better way to handle it in pure batch is:
- Send the output of the program to a temporary file
- Check the error level
- If there are no errors process the file output
- In any case delete the temporary file at end
Something like
set "tempFile=%temp%\%~n0.%random%%random%%random%.tmp" > "%tempFile%" 2>&1 ( PSQL -U userName -d dbName -t -c "SELECT * FROM nonExistantTable" ) if not errorlevel 1 ( for /f "usebackq delims=" %%g in ("%tempFile%") do ( echo %%g ) ) else ( echo ERRORLEVEL: %errorlevel% ) del /q "%tempFile%"
这篇关于批次For循环中的PSQL错误级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!