Run SQL Script Against MySQL Using Powershell

I have a Powershell script that supports my MySQL DB every night using mysqldump. This all works fine, but I would like to extend the script to update the db (db1) report from the backup prod db (db2). I wrote the following test script, but it does not work. I feel the problem is reading the sql file in CommandText, but I'm not sure how to debug it.

[system.reflection.assembly]::LoadWithPartialName("MySql.Data")    
$mysql_server = "localhost"
$mysql_user = "root"
$mysql_password = "password"
write-host "Create coonection to db1"
# Connect to MySQL database 'db1'

$cn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$cn.ConnectionString = "SERVER=$mysql_server;DATABASE=db1;UID=$mysql_user;PWD=$mysql_password"
$cn.Open()
write-host "Running backup script against db1"
# Run Update Script MySQL 
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql = Get-Content C:\db2.sql
$cm.Connection = $cn
$cm.CommandText = $sql
$cm.ExecuteReader()
write-host "Closing Connection"
$cn.Close()

Any help would be greatly appreciated. Thank.

+3
source share
1 answer

This line:

$sql = Get-Content C:\db2.sql 

. - , PowerShell , $OFS ( ). , . , :

$sql = Get-Content C:\db2.sql 
...
$OFS = "`r`n"
$cm.CommandText = "$sql"

, PowerShell 2.0:

$sql = (Get-Content C:\db2.sql) -join "`r`n"
+3

Source: https://habr.com/ru/post/1785201/


All Articles