I'm looking for the "idiots guide" on how to connect Powershell to a MySQL database.  Specifically the K1000 ORG1 database.

I have MySQL Workbench connected and have no problem building the needed queries, I just need to be able to run those queries using Powershell.

I have an ODBC connection to the KACE database but after that I'm going beyond my knowledge.

I've tried the below with no luck.  But I am completely guessing based on Google searches. 

$connectstring = "DSN=K1000;"
 $sql = "select * from HD_Ticket"
 $conn = New-Object System.Data.Odbc.OdbcConnection($connectstring)
 $cmd = New-Object system.Data.Odbc.OdbcCommand($sql,$conn)
 $da = New-Object system.Data.Odbc.OdbcDataAdapter($cmd)
 $dt = New-Object system.Data.datatable
 $null = $da.fill($dt)

Running the above gives the following:

Exception calling "Fill" with "1" argument(s): "ERROR [42S02] [MySQL][ODBC 5.3(w) Driver][mysqld-5.6.10-log]Table 'ORG1.HD_Ticket' doesn't exist"
At C:\test\connecttomysql.ps1:12 char:2
+  $null = $da.fill($dt)
+  ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OdbcException

0 Comments   [ - ] Hide Comments


Please log in to comment

Community Chosen Answer



I was able to connect with the following:

$cn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection

$cn.ConnectionString = "SERVER=X.X.X.X;DATABASE=ORG1;UID=user;PWD=password"

$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$cm.Connection = $cn
$cm.CommandText = $sql
$dr = $cm.ExecuteReader()
while($dr.Read()){ $dr.GetString(0) }

Answered 07/27/2015 by: mds1981
Orange Belt

Please log in to comment
Answer this question or Comment on this question for clarity


Just making sure that you know access to the ORG1 KACE database is read only, and as such you will not be able to run any updates to the database using scripts
Answered 07/27/2015 by: Hobbsy
Red Belt

  • Correct, I am not trying to run any updates, just queries.
Please log in to comment