需要帮助解决这个问题:我需要从MySQL DB获取表数据以便在脚本中进一步使用。我正在使用此代码访问MySQL数据:
[void][System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector Net 6.7.4\Assemblies\v2.0\MySql.Data.dll")
$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") | Out-Null
$Command.Dispose()
$Table=$DataSet.Tables["data"] | FT -auto
$Connection.Close()
$Table
它给了我我珍贵的垃圾:
TASKID TASKTYPE fistNAME secNAME STATUS ------ -------- -------- ------- ------ 1111 1 Dep1 0 2222 2 User321 Dep1 0
但是当我尝试时,例如将结果导出为CSV:
Export-Csv -Path "c:\test.csv" -InputObject $Table
我得到的是:
#TYPE System.Object[] "Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized" "6","6","6","1","System.Object[]","False","True","False"
所以当我尝试解析变量中的数据时,如下所示:
Write-Host $Table
foreach ($Task in $Table) {
Write-Host $Task.TASKID
}
我得到的是:
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
任何人都可以帮我解决这个问题吗?
这条线
$Table=$DataSet.Tables["data"] | FT -auto
将您的数据转换为FormatStartData
对象数组。
如果要导出数据,请不要将数据传输到Format-Table
。试试这个:
$DataSet.Tables["data"] | Export-Csv "c:\test.csv"