powershell - 执行powershell语句后检测错误

标签 powershell sqlplus

我正在使用 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

Does the powershell statement return an errorlevel after the statement is executed like DOS?

I have tried:

& '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变量或sqlplus的返回值。在 PowerShell 中,每个变量都有一个 $字首。

关于powershell - 执行powershell语句后检测错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43679555/

相关文章:

powershell - 如何在 PowerShell 中将诸如 5.7303333333e+02 之类的字符串转换为十进制?

powershell忽略来自不同进程的输出的字符转义

powershell - 将文件从Windows复制到多个linux系统的powershell脚本

osx-lion - ORA-12162 : TNS:net service name is incorrectly specified on Mac OS X Lion

bash - 从 PL/SQL Developer 和 SQL*plus 调用时,存储过程没有相同的结果

python - 使用 (wx)python 记录外部程序的输出

powershell - 识别Powershell中执行批处理文件的PID

带 RunspacePool 的 C# PowerShell - 如何导入 Exchange Cmdlet,如 Get-Mailbox?

linux - bash 上的 sqlplus 输入重定向

sql - 此处不允许使用分组功能