【问题标题】:PowerShell 4 SQL Server InsertionsPowerShell 4 SQL Server 插入
【发布时间】:2017-01-11 13:27:57
【问题描述】:

我正在使用 Powershell 4 并尝试将数据写入 SQL Server 2012。

这是我正在使用的脚本

Add-Type -AssemblyName System.Data

$conn = New-Object System.Data.SqlClient.SqlConnection↵
$conn.ConnectionString = "Data Source=<SQLSERVER>;Initial Catalog=SYSINFO;Integrated Security=true;"
$conn.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand

我得到的错误是:

New-Object : Cannot find type [System.Data.SqlClient.SqlConnection] : verify that the assembly containing this type is loaded.

我假设第一行 (Add-Type) 将加载 System.Data 下的所有必需程序集

我是否遗漏了一些明显的东西?

【问题讨论】:

  • 能不能用-PassThru看看是否真的加了SQLConnection类型?类似于 Add-Type -AssemblyName "System.Data" -PassThru | ForEach-Object { if($_.Name -eq "SqlConnection") { $_ } }
  • Invoke-Sqlcmd 可能更容易。

标签: powershell powershell-4.0


【解决方案1】:

你可以这样做:

$Server = 'theServer'    
$database = 'theDatabase'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server=$($Server);database=$($Database);trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = 'SELECT TOP 5 *  FROM yourTable ORDER BY 1 DESC'
$Reader = $Command.ExecuteReader()
$Datatable = New-Object System.Data.DataTable
$Datatable.Load($Reader)
$Datatable | Export-Csv  report.csv -NoTypeInformation
$Connection.Close() 

【讨论】:

  • 我很乐意提供帮助:)
猜你喜欢
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
相关资源
最近更新 更多