PowerShell 4 SQL 服务器插入

PowerShell 4 SQL Server Insertions

我正在使用 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

下加载所有必需的程序集

我是不是漏掉了一些明显的东西?

你可以这样做:

$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()