我有我的方法(除非我做了一些愚蠢的事情)昨天完美地工作导出到csv。但是,今天我不断得到这个错误:
异常通话"填写"用" 1"参数:" ExecuteReader:CommandText属性尚未初始化"
- $ rowCount时= $ SqlAdapter.Fill($ DT)
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- CategoryInfo:NotSpecified:(:) [],MethodInvocationException
- FullyQualifiedErrorId:InvalidOperationException
这是我的语法:
$server = "serverinstance"
$database = "databaseinstance"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "Select Top 1 * from madeuptable"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)
$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)
if ($rowCount -gt 0) { $dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation }
$connection.Close()
答案 0 :(得分:0)
尝试使用查询和连接创建SqlDataAdaper(并删除cmd)。
示例:
$SqlAdapter = new-object system.data.sqlclient.sqldataadapter ($SelectQuery, $connection)
答案 1 :(得分:0)
我会检查你的$ server和$ database变量。我只是对我自己的SQL服务器运行你的脚本,它对我来说很好。
编辑:
这是我跑的:
$server = "FAR-L2484\HOLDER_SQL" ## Hostname\InstanceID
$database = "MASTER"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "SELECT * FROM information_schema.tables"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)
$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)
$dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation
$connection.Close()
这就是我在C:\ test \ sqlresults.csv
中得到的"TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","TABLE_TYPE"
"master","dbo","spt_fallback_db","BASE TABLE"
"master","dbo","spt_fallback_dev","BASE TABLE"
"master","dbo","spt_fallback_usg","BASE TABLE"
"master","dbo","spt_values","VIEW"
"master","dbo","spt_monitor","BASE TABLE"
"master","dbo","MSreplication_options","BASE TABLE"