0

I'm relatively new to powershell scripting so I have been coding based on multiple examples that I have seen online.

I have a script that executes multiple batch files in parallel and each batch file contains a bcp command to execute. I'm trying to catch any errors that may occur running the batch file but it's not working as expected. I specifically forced an error on product.bat by having an invalid select syntax.

workflow Test-Workflow 
{
    Param ([string[]] $file_names)
    $file_names = Get-Content "D:/EDW/data/informatica/ming/Powersh/bcplist.lst"
    foreach -parallel ($line in $file_names) 
    {
       try
       {
          Write-Output ("processing... " + $line + ".bat")
          start-process D:/EDW/data/informatica/ming/Powersh/$line.bat -ErrorAction Stop -wait
       }
       catch
       {
          $ErrorMessage = $_.Exception.Message
          $FailedItem = $_.Exception.ItemName
          Write-Output $line : $ErrorMessage  $FailedItem
       }
   }
}
bcplist.lst:
        ing_channel
        ing_product
ing_channel:
        bcp "SELECT  * FROM CHANNEL" queryout ing_channel.txt -T -S99.999.999.9,99999 -t"\t" -c -q
ing_product:
        bcp "SELT  * FROM PRODUCT" queryout ing_product.txt -T -S99.999.999.9,99999 -t"\t" -c -q

Any help or suggestion would be greatly appreciated.

1
  • BAT files are not PoSh code ... and they don't trigger a stop error ... and the try/catch construct REQUIRES a stop error. ///// why are you using BAT files? the bcp.exe util should run properly when called from in a ps1 file. ///// also, the bcp.exe util seems to be doing SQL queries ... and powershell has cmdlets for that ... so, why use that util instead of the PoSh cmdlets? Commented Dec 27, 2019 at 15:20

1 Answer 1

2

Exceptions are only thrown/caught when terminating errors are thrown, which are only thrown by cmdlets, .NET libraries, or native code when P/Invoke is in play. In order to handle failures with external commands, such as checking whether a bat or exe succeeded, you will need to check the $LASTEXITCODE yourself. $LASTEXITCODE is the PowerShell equivalent of %ERRORLEVEL% in cmd.exe. Here is an example of some basic boilerplate code to check this for the ping command:

&ping nonexistant.domain.tld
if( $LASTEXITCODE -ne 0 ){
  # Handle the error here
  # This example writes to the error stream and throws a terminating error
  Write-Error "Unable to ping server, ping returned $LASTEXITCODE" -EA Stop
}

Note that the -ErrorAction argument has a shorthand of -EA, so either the long or short form will work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.