Powershell to read from database using ODBC DSN instead of connection string

Glowie picture Glowie · Aug 14, 2014 · Viewed 37.6k times · Source

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?

Answer

andyb picture andyb · Aug 14, 2014

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.