简体   繁体   中英

How would I go about error handling with a Powershell object in c#?

I have a short Powershell script:

$spName = $args[0]
$filterList = $args[1]
$destinationFile = $args[2]
$server = $args[3]
$user = $args[4]
$password = $args[5]
bcp "EXEC $spName @FilterList = $filterList" queryout "$destinationFile" -c -t"\0" -S $server -U $user -P $password

I am using the Powershell object in .Net to add the arguments and call the Invoke method. I had a problem, though, when the password was wrong. It locked the DB down. Much embarrassment. At no point, however, was an exception thrown. I know that the .Net Pipeline object has an Error method that returns a collection of errors, but I don't know how I would implement a pipeline with this script. Is there a command for bcp? Do I just add that script as a command? Otherwise, is there a way to implement error handling with the powershell object? Any help you guys and gals can offer will be appreciated.

For error handling in PowerShell, there is a try/catch mechanism similar to C#'s that you can implement.

However, that only works of a PowerShell exception is thrown along the way. In this case I doubt BCP is thrown any exceptions, which is why your script finished without error. Instead you'll need to rely on whatever error trapping mechanism bcp supports. In this case there are a couple of parameters that look useful:

-m max_errors

Specifies the maximum number of syntax errors and compilation errors that can occur before the bulk copy operation is canceled.

-e err_file

Specifies the full path of an error file used to store any rows bcp is unable to transfer from the file to the database.

In addition, if BCP sets an error code on exit, which many old-style command line utilities do, there are a pair of pre-defined PowerShell variables that hold the result of the last command executed:

$LastExitCode # Holds the actual error code
$?            # Holds $True if $LastExitCode was 0, $False otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM