Here is the command I have been using to back up one of my MySQL databases:
mysqldump.exe --user=myuser --password=mypassword --databases --opt MyDatabase > "C:\MyDatabase.sql"
I’d like to use this command in a PowerShell script. However, if an error occurs, I don’t want it to be outputted to the console. Instead, I would like it captured in a variable. I’ve been trying various methods of doing this, but all have failed. Any assistance would be appreciated. Thanks!
Firstly, beware
>if your database dump does not need to be in Unicode, but rather ASCII. You would instead use| out-file $filepath -enc asciito make sure it writes in ASCII encoding. (My databases are in latin1. If I use Powershell’s>the dump file is twice as large as when dumped using>from normal console.)That said, I got it to dump to a file in ASCII format and put the errors in a variable in this way (forcing an error by trying to dump a nonexistent database, but mysqldump outputs a number of initializing lines of the dump before it throws the error):
This wraps the execution so that stdout is piped to
out-file, but after that wrapping, stderr is redirected to stdout so that it can be assigned to variable $err.$erris 1ErrorRecordor more. A single error has aTargetObjectproperty containing the original stderr output. Here’s a demo of printing every error string to the console:Alternately, you can ensure that
$erris an array by slightly modifying the original dump statement by wrapping it an@()(good idea, Mike):