none
powershell - Try/Catch and external exe (like sqlcmd)

    Question

  • Hello,

    How Can I catch errors from exetrenal programs like sqlcmd, bcp, and other tools.

    I'd like catch error (generally sql server error)

     

    Msg 102, Level
    
     15, State 1, Server BILL2K8, Line 1
    Incorrect syntax near 'SSSSSSselect'
    
    .
    

    and write it to some text log file, bellow block does't catch error:

    try {
    	sqlcmd -E -SBILL2K8 -Q "set nocount on; SSSselect @@version;" -b -h-1
    } 
    
    catch {
    	Write-Output "ERR!!!" | Out-File .\error_log.txt
    } 

     

     

     

     

     

    Thursday, September 9, 2010 11:29 PM

Answers

  • PowerShell can't deal with errors from command-line EXEs.  You should get $LASTEXITCODE after running the EXE to determine the return code and deal with it appropriately.
    Wednesday, October 20, 2010 9:10 PM
    Moderator

All replies

  • The Try/Catch only catches terminating errors. Before the Try/Catch, add this: $erroractionpreference = 'stop'. This way if any error occurs, it will be treated as a terminating error.

    http://technet.microsoft.com/en-us/library/dd315350.aspx

    Friday, September 10, 2010 1:48 AM
    Moderator
  • Hello,

     

    Thank you, but adding $erroractionpreference = 'stop' didn't resolve problem. Can you help me how I can catch errors from sql server and sqlcmd to file?

    Wednesday, September 15, 2010 7:38 PM
  • PowerShell can't deal with errors from command-line EXEs.  You should get $LASTEXITCODE after running the EXE to determine the return code and deal with it appropriately.
    Wednesday, October 20, 2010 9:10 PM
    Moderator
  • That solution doesn't work either.

    In my case I have a .NET application throwing an exception and popping up a JIT debugger window. I cannot escape it unless I click on the button.

    After I click the button the $LastExitCode finally runs.

    Thursday, December 6, 2018 10:51 AM