Windows OS Hub
  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux
  • Home
  • About

Windows OS Hub

  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux

 Windows OS Hub / PowerShell / How to Connect and Query MySQL or MariaDB with PowerShell

March 17, 2024 PowerShellWindows 11Windows Server 2019

How to Connect and Query MySQL or MariaDB with PowerShell

You can connect to a MySQL/MariaDB database, select data from a table, and add, update, and delete table entries directly from a PowerShell script. In this post, we’ll look at simple ways to run SQL queries against a remote MySQL (MariaDB) database from the PowerShell.

Contents:
  • How to Query a MariaDB or MySQL Database from PowerShell
  • Running SQL Queries from PowerShell Using the MySQL Connector

First, check that the remote SQL server is accepting remote connections from your host on the default port TCP 3306:

Test-NetConnection mysqlDBserver -port 3306

On the MySQL server, allow users to connect remotely from your IP address or any host (replace IP with %):

GRANT ALL ON myDB.* to 'dbadmin'@'10.2.1.10' IDENTIFIED BY 'Passw0rd1!'  WITH GRANT OPTION;
FLUSH PRIVILEGES;

How to Query a MariaDB or MySQL Database from PowerShell

You can use the SimplySql universal PowerShell module to connect to the MySQL/MariaDB database and run SQL queries. Install this module from the PowerShell Online Gallery:

Install-Module -Name SimplySql

install powershell module simplysql

The Open-MySQLConnection cmdlet is used to connect to the MariaDB/MySQL server and the Invoke-SQLQuery to execute SQL queries.

Save the db username and password for the MySQL server connection:

$DBUser = "dbadmin"
$DBPassword = ConvertTo-SecureString -String "Passw0rd1!" -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $DBUser, $DBPassword

Connect to a MySQL/MariaDB database on a remote server:

$sqlConnect = Open-MySqlConnection -ConnectionName MyDBCon -Server 10.2.1.129 -Database myDB -Port 3306 -Credential $creds -WarningAction SilentlyContinue

Run a parameterized query against the MySQL database:

$cityname="Munich"
$data = Invoke-SqlQuery -query "SELECT * FROM myDB WHERE city like '%$cityname%'"

powershell Invoke-SqlQuery query

Insert data into the table:

Invoke-SqlQuery -query "INSERT INTO myDB (name,phone,id,city,email) VALUES  ('Alfred','+49-30-054758864',1233,'Munich',[email protected]')"

Update cell value in MySQL table:

Invoke-SqlQuery -query "UPDATE myDB SET city = 'Munich' WHERE ID = 1233"

Close the database connection:

Close-SqlConnection -connectionname MyDBCon

Running SQL Queries from PowerShell Using the MySQL Connector

To connect to the MySQL or MariaDB database server, you can use the official MySQL .NET Connector, which is available for free download from the MySQL website. Download the latest version of the connector and install it on your computer (https://dev.mysql.com/downloads/connector/net/).

Install MySQL .NET Connector on Windows

It is not necessary to install the MySQL .NET Connector MSI package, just copy the MySql.Data.dll library file to your computer. 

The following PowerShell script gets a list of users and their email addresses from Active Directory and writes them to a MySQL database (the Get-ADUser cmdlet is used to list user accounts in AD):

# connecting the MySql.Data.dll library
[void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector NET 8.3.0\MySql.Data.dll")
$mysql_server = "10.2.1.129"
$mysql_user = "dbadmin"
$mysql_password = "Passw0rd1!"
$dbName = "TestDB"
$Connection = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = "SERVER=$mysql_server;DATABASE=$dbName;UID=$mysql_user;PWD=$mysql_password"
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
#prepare a list of users from specific OU containing names and e-mail addresses
Import-Module activedirectory
$UserList=Get-ADUser -SearchBase ‘OU=Users,OU=Paris,DC=adatum,DC=com’ -filter * -properties name, EmailAddress
ForEach($user in $UserList)
{
$uname=$user.Name;
$uemail=$user.EmailAddress;
#write the information about each use to the database table
$sql.CommandText = "INSERT INTO users (Name,Email) VALUES ('$uname','$uemail')"
$sql.ExecuteNonQuery()
}
$Reader.Close()
$Connection.Close()

Powershell Write data to mysql db

The following script uses an SQL SELECT query to retrieve data from a database table and display it in the PowerShell console.
Set-ExecutionPolicy RemoteSigned
[void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector NET 8.3.0\MySql.Data.dll")
$mysql_server = "10.2.1.129"
$mysql_user = "dbadmin"
$mysql_password = "Passw0rd1!"
$dbName = "TestDB"
$Connection = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = "SERVER=$mysql_server;DATABASE=$dbName;UID=$mysql_user;PWD=$mysql_password"
$Connection.Open()
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$MYSQLDataSet = New-Object System.Data.DataSet
$MYSQLCommand.Connection=$Connection
$MYSQLCommand.CommandText='SELECT * from  users'
$MYSQLDataAdapter.SelectCommand=$MYSQLCommand
$NumberOfDataSets=$MYSQLDataAdapter.Fill($MYSQLDataSet, "data")
foreach($DataSet in $MYSQLDataSet.tables[0])
{
write-host "User:" $DataSet.name  "Email:" $DataSet.email
}
$Connection.Close()

posh: select query from mysql

In one of the previous articles, we looked at an example of using a MySQL (MariaDB) database to store information from Windows Event logs: How to find out who deleted files from a shared folder in Windows. 
3 comments
1
Facebook Twitter Google + Pinterest
previous post
Fixing High Memory Usage by Metafile on Windows Server 2008 R2
next post
Configuring Kerberos Authentication on IIS Website

Related Reading

How to Cancel Windows Update Pending Restart Loop

May 6, 2025

View Windows Update History with PowerShell (CMD)

April 30, 2025

Change BIOS from Legacy to UEFI without Reinstalling...

April 21, 2025

Remove ‘Your License isn’t Genuine’ Banner in MS...

April 21, 2025

Uninstalling Windows Updates via CMD/PowerShell

April 18, 2025

3 comments

Paulo January 15, 2019 - 10:09 pm

Hi, I am learning my way around powershell and kind of new to trying to create my own script. I was kind of working my way around with your script and attempted write my own but I can’t seem to figure it out. I am basically trying to use powershell to query MySQL and check if Last_IO_Error, is Slave_IO_Running, Slave_SQL_Running and Seconds_Behind_Master=0 Would you happen to have any suggestions? Thanks Paul

Reply
ThierryC March 7, 2024 - 10:42 pm

Funny how the code in the picture does not match the code in the article, if using the code in the article, the connection is refused especially if the server runs on a different port than the default one. Using the code in the article fails too… How do you do?

Reply
ThierryC March 7, 2024 - 10:54 pm

Update: Using the codes on MariaDB is the thing that do not work, sorry. (https://bugs.mysql.com/bug.php?id=109331)

Reply

Leave a Comment Cancel Reply

join us telegram channel https://t.me/woshub
Join WindowsHub Telegram channel to get the latest updates!

Categories

  • Active Directory
  • Group Policies
  • Exchange Server
  • Microsoft 365
  • Azure
  • Windows 11
  • Windows 10
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • PowerShell
  • VMware
  • Hyper-V
  • Linux
  • MS Office

Recent Posts

  • Cannot Install Network Adapter Drivers on Windows Server

    April 29, 2025
  • Change BIOS from Legacy to UEFI without Reinstalling Windows

    April 21, 2025
  • How to Prefer IPv4 over IPv6 in Windows Networks

    April 9, 2025
  • Load Drivers from WinPE or Recovery CMD

    March 26, 2025
  • How to Block Common (Weak) Passwords in Active Directory

    March 25, 2025
  • Fix: The referenced assembly could not be found error (0x80073701) on Windows

    March 17, 2025
  • Exclude a Specific User or Computer from Group Policy

    March 12, 2025
  • AD Domain Join: Computer Account Re-use Blocked

    March 11, 2025
  • How to Write Logs to the Windows Event Viewer from PowerShell/CMD

    March 3, 2025
  • How to Hide (Block) a Specific Windows Update

    February 25, 2025

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • How to Unblock a File Downloaded from Internet on Windows
  • Windows: Auto Reconnect to VPN on Disconnect
  • PowerShell Remoting via WinRM for Non-Admin Users
  • How to Clear Event Viewer Logs on Windows
Footer Logo

@2014 - 2024 - Windows OS Hub. All about operating systems for sysadmins


Back To Top