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?

1
  • Did the answer below work for you? Commented Sep 16, 2014 at 14:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Robino yes it worked, even with encrypted $password $qt = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1"), $SQL1)
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'."
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()

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.