Script for MySQL backup to multiple files

假装没事ソ 提交于 2019-12-11 23:15:53

问题


I am creating a script to back up the MySQL running on a Windows 2012 server, using PowerShell. Unlike other tips found here, I want to generate a .sql file for each of the databases.

This post shows how to create multiple files. I adapted it to PowerShell:

Get-ChildItem -Path "$($MYSQL_HOME)\data" | cmd /C "$($MYSQL_HOME)\bin\ mysql -u -s -r $($dbuser) -p$($dbpass) -e 'databases show' '| while read dbname; cmd /C "$($MYSQL_HOME)\bin\mysqldump.exe --user = $($dbuser) --password = $($dbpass) --databases $dbname> $($BKP_FOLDER)\$dbname($BACKUPDATE).sql "

but it returns error in while.

What should I change so that you can generate multiple .sql, one for each database?


回答1:


Your entire commandline is b0rken. Throw it away and start over. Try something like this:

Set-Location "$MYSQL_HOME\bin"
& .\mysql.exe -N -s -r -u $dbuser -p$dbpass -e 'show databases' | % {
  & .\mysqldump.exe -u $dbuser -p$dbpass --single-transaction $_ |
    Out-File "$BKP_FOLDER\${_}$BACKUPDATE.sql" -Encoding Ascii
}



回答2:


Example using an input from file result of mysqldump.

#Variables#####
# Debe especificar la ruta completa, por ejemplo C:\Temp\archivo.txt
$file = $args[0]
$c = ""
$i = 0
$startSafe = 0;
###############

New-Item -ItemType Directory -Force -Path .\data
$x = 0;
foreach ($f in [System.IO.File]::ReadLines($file)) {
    if ($f -like '-- Dumping data for table *') {
        $startSafe = 1;
        $x = $f.split('`')[1];
        write $x;
    }
    if ($startSafe) {
        if($f -eq "UNLOCK TABLES;"){$i += 1; $f >> .\data\$x.out.sql; $startSafe = 0; $x = $i}
        if($f -ne "UNLOCK TABLES;"){ $f >> .\data\$x.out.sql;}
    }
}


来源:https://stackoverflow.com/questions/36090916/script-for-mysql-backup-to-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!