在powershell脚本中的excel中调用SQL查询

时间:2014-08-06 19:59:26

标签: sql excel powershell

我试图在PowerShell脚本中调用EXCEL工作表中的SQL查询,因此查询将打印到EXCEL工作表

$username = $credentials.UserName
$password = $credentials.GetNetworkCredential().Password
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=10.10.10.10;Initial Catalog=database;User Id=$username;Password=$password;"

$excel = New-Object -Com Excel.Application
$excel.Visible = $True
$wb = $Excel.Workbooks.Add()
$currentWorksheet=1

if ($currentWorksheet -lt 4){
    $ws = $wb.Worksheets.Item($currentWorksheet)
}
else
{
    $ws = $wb.Worksheets.Add()
}

$currentWorksheet += 1
    $qt = $ws.QueryTables.Add($conn.ConnectionString, $ws.Range("A1"), $SQL)

当我运行脚本时,我收到错误

Exception calling "Add" with "3" argument(s): "Exception from HRESULT: 0x800A03EC"

我以为我在$ ws.QueryTables.Add中输入正确数量的参数和值(

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我必须创建DSN,如此处所示

http://blog.mclaughlinsoftware.com/2012/09/12/sql-server-odbc-osn/

然后我在脚本开头创建了变量

$DSN = 'SQL Server ODBC' (same as the example)

现在,$ qt的值已更改,

$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN", $ws.Range("A1"), $SQL)