我需要创建一个连接到MySQL实例的PowerShell脚本,运行查询并将结果解析为XML。我从这里开始:
Param(
[Parameter(
Mandatory = $true,
ParameterSetName = '',
ValueFromPipeline = $true)]
[string]$Query
)
$MySQLAdminUserName = 'adminuser'
$MySQLAdminPassword = 'password'
$MySQLDatabase = 'mysql'
$MySQLHost = '192.168.10.126'
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword + ";database="+$MySQLDatabase
try {
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
$DataSet.Tables[0]
} catch {
Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
} finally {
$Connection.Close()
}
脚本返回表,但无论如何我无法将结果格式化为XML。你能帮我解决这个问题吗?我打算运行的所有查询都会显示2列。
答案 0 :(得分:0)
尝试类似这样的事情
$DataSet.Tables[0].WriteXML('c:\temp\result.xml')
或者
[xml] $xml=$DataSet.Tables[0] | ConvertTo-XML -NoTypeInformation
答案 1 :(得分:0)
对于这种简单的完整XML构造可能有点过分。您只需将表值插入字符串模板,如下所示:
$results = $DataSet.Tables[0] | ForEach-Object {
'<result><channel>{0}</channel><value>{1}</value></result>' -f $_.col1, $_.col2
}
$prtg = "<prtg>{0}</prtg>" -f (-join $results)
将col1
和col2
替换为实际的字段名称。