5

I know how to read value from database using connectionstring, i.e.

Establish database connection to read

$conn = New-Object System.Data.SqlClient.SqlConnection

$conn.ConnectionString = "Server=10.10.10.10;Initial Catalog=database_name;User Id=$username;Password=$password;"

$SQL = "..."

$conn.Open()

# Create and execute the SQL Query

$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)

$count=0
do{
    try{
        $rdr = $cmd.ExecuteReader()



        while ($rdr.read()){
            $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1))
            $count=$count + 1
        }
        $transactionComplete = $true

    }
    catch{
        $transactionComplete = $false
    }
}until ($transactionComplete)



# Close the database connection

$conn.Close()

How can I accomplish the same thing with ODBC, i.e I have DSN (data source name) set up on the server?

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Glowie
  • 2,271
  • 21
  • 60
  • 104

3 Answers3

9

According to https://www.connectionstrings.com/odbc-dsn/ you would use something like...

DSN=myDsn;Uid=myUsername;Pwd=;

Can probably just go with DSN=... if creds not required.

andyb
  • 2,722
  • 1
  • 18
  • 17
  • @Robino yes it worked, even with encrypted $password `$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1"), $SQL1)` – Glowie Sep 17 '14 at 13:28
  • 1
    This didn't work for me either for the SqlClient, this works for an ODBC connection. With the SqlClient I get the following error: Exception calling ".ctor" with "1" argument(s): "Keyword not supported: 'dsn'." – Douglas Plumley Nov 06 '17 at 19:12
8

This works if your ODBC connection is under User DSN but not under System DSN. I cannot find a way to make it check for System DSN connections.

$conn = new-object System.Data.Odbc.OdbcConnection
$conn.connectionstring = "DSN=DSNNAME"
$conn.open()

$cmd = New-object System.Data.Odbc.OdbcCommand($sqlCommand,$conn)
$dataset = New-Object System.Data.DataSet
(New-Object System.Data.Odbc.OdbcDataAdapter($cmd)).Fill($dataSet) | Out- Null
$conn.Close()
Iconiu
  • 367
  • 4
  • 5
1

You may want to put this in front of the code...

If you want to do it on your local machine instead of in the context of SQL server then I would use the following. It is what we use at my company.

if ($env:Processor_Architecture -ne "x86")   
{ write-warning 'Launching x86 PowerShell'
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noninteractive -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass
exit
}

Always running in 32bit PowerShell at this point.

$env:Processor_Architecture
Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
Cary
  • 11
  • 1