Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting error after a powershell statement is executed

Tags:

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.

& '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:

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

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;
}

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:

if ($LASTEXITCODE -ne 0 )
{ 
write-host error;
}
else
{ 
write-host ok;
}
like image 837
user1205746 Avatar asked Apr 28 '17 11:04

user1205746


1 Answers

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.

like image 119
Martin Brandl Avatar answered Sep 21 '22 13:09

Martin Brandl