问题
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:
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
-ErrorActionargument has a shorthand of-EA, so either the long or short form will work.
来源:https://stackoverflow.com/questions/59502585/catching-errors-in-powershell-workflow