执行 powershell 语句后检测错误

Detecting error after a powershell statement is executed

我正在使用 powershell 运行 sqlplus 我希望 PowerShell 检测脚本 运行 后是否有错误并执行一些操作而不是我看结果文件。

& 'sqlplus' 'system/myOraclePassword' '@Test' | out-file 'result.txt';

一般在DOS下,命令遇到错误时会出现%errorlevel%,不知PowerShell中是否有类似的东西?

当然,我可以自己阅读日志文件,但有时,事情太过常规,我可能会忘记。

我的Test.sql:

select level from dual
connect by level<5;
select 10/0 from dual;
quit;

明显有被零除的错误。 result.txt 捕获它,但我希望 powershell 也能检测到它

SQL*Plus: Release 12.1.0.2.0 Production on Thu Apr 27 16:24:30 2017

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Last Successful login time: Thu Apr 27 2017 16:17:34 -04:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options


     LEVEL
----------
     1
     2
     3
     4

select 10/0 from dual
         *
ERROR at line 1:
ORA-01476: divisor is equal to zero

powershell语句return是否像DOS一样执行后出现errorlevel?

我试过:

& 'sqlplus' 'system/myOraclePassword' '@Test' | out-file 'result.txt';
if (errorlevel 1)
{ write-host error;
}
else
{ write-host ok;
}

但这导致了语法错误?

errorlevel : The term 'errorlevel' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

在 powershell 中检查错误的正确方法是什么?

更新

我用过这个:

if ($LASTEXITCODE -ne 0 )
{ 
write-host error;
}
else
{ 
write-host ok;
}

由于您正在调用 可执行文件,您可能想要检查 $LASTEXITCODE 变量或 return 值 的 sqlplus。在 PowerShell 中,每个变量都有一个 $ 前缀。