Powershell og mysql

rated by 0 users
This post has 1 Reply | 2 Followers

Not Ranked
Posts 1
bjornsvgs Posted: 11-30-2011 1:07 PM

Is it possible to query one record (a number) from a column in mysql database and put that into a textfile by using Powershell.

I use "select [column1] from [table1] where [column2]='$computername'
but I don't know how to get the record from there to a textfile?
Hope for an answer (an example)
Top 10 Contributor
Posts 658
Idera Employee

In theory you should be able to use MySql .Net Client to run a query, store result in a dataset and then output the table[0[ to a CSV file using Export-CSV. Not tested, but it would look something like this:

 

#Set credentials
$credentials = Get-Credential
$cred = $credentials.GetNetworkCredential()
$uid = $cred.UserName
$pwd = $cred.Password

# Open Connection
$connStr = "server=$server;port=$port;uid=$uid;pwd=$pwd;database=$db;Pooling=False"
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
$conn.Open()

# Create a MySqlCommand and MySqlDataAdapter object
$query = "select [column1] from [table1] where [column2]='$computername'" #--> your complete select statement
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $conn)
$da = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)

# Populate a dataset and output the query result
$ds = New-Object System.Data.DataSet
$da.Fill($ds)
$path = {filepath to output results: i.e. C:\results.csv}
$ds.Tables[0] | Export-Csv -Path $path

Page 1 of 1 (2 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.