Which command populates the database with an existing .sql file in Powershell

Im writing a script in powershell that needs to connect to the MySQL server, create a new database and then run query commands with this database. I have a ready .sql file with all the commands that will be executed, but there seems to be a problem with my code where it never executes the .sql file. Any help would be greatly appreciated. My code is below.

[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data")

#Creates a connection to the server
$connStr ="server=mySql;Persist Security Info=false;user id=" + "username" + ";pwd=" + "pass" + ";"
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)

#Open connection
$conn.Open()

#Drops database if it currently exists
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$cmd.Connection  = $conn
$cmd.CommandText = "DROP DATABASE IF EXISTS " + $dbname
$cmd.ExecuteNonQuery()

#Create the new database
$cmd.CommandText = 'CREATE SCHEMA `' + $dbname + '`'
$cmd.ExecuteNonQuery()

#Load the sql file
$sql = (Get-Content C:\"path to sql file") -join "'r'n"
$cmd.CommandText = $sql

#Close connection
$conn.Close()
+3
source share
1 answer

$cmd.ExecuteNonQuery()? , "r'n". (, "` R`n" ). Out-String :

#Load the sql file
$sql = Get-Content C:\"path to sql file" | Out-String
$cmd.CommandText = $sql
$cmd.ExecuteNonQuery()
+1

All Articles