Question:
I am using powershell to run sqlplus
and I would like PowerShell to detect if there are error after the script was run and to perform some action instead of me looking at the result file.
1 2 |
& 'sqlplus' 'system/myOraclePassword' '@Test' | out-file 'result.txt'; |
Normally in DOS, there is %errorlevel% when the command encounters error and I wonder if there is similar stuff in PowerShell?
Of course, I can read the log file myself but sometimes, thing got too routine and I may forget.
My Test.sql:
1 2 3 4 5 |
select level from dual connect by level<5; select 10/0 from dual; quit; |
There is clearly a division by zero error. The result.txt captures it but I would like powershell to detect it as well
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 3 4 5 6 7 8 |
& 'sqlplus' 'system/myOraclePassword' '@Test' | out-file 'result.txt'; if (errorlevel 1) { write-host error; } else { write-host ok; } |
But that has caused syntax error?
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.
What is a proper way to check error in powershell?
UPDATE
I used this:
1 2 3 4 5 6 7 8 9 |
if ($LASTEXITCODE -ne 0 ) { write-host error; } else { write-host ok; } |
Answer:
Since you are invoking an executable, you probably want to check for the $LASTEXITCODE
variable or the return value of sqlplus. In PowerShell each variable has a $
prefix.