Mikael
Mikael

Reputation: 191

How to connect to ODBC in Powershell?

How can I connect to odbc from powershell?

I have found this function:

function Get-ODBC-Data{

   param(

   [string]$query=$('select count(*) from [master].[sys].[table_name]'),

   )

  $conn = New-Object System.Data.Odbc.OdbcConnection

  $conn.ConnectionString = "DSN=AllSecure;"

  $conn.open()

  $cmd = New-object System.Data.Odbc.OdbcCommand($query,$conn)

  $ds = New-Object system.Data.DataSet

  (New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($ds) | out-null

  $conn.close()

  $ds.Tables[0]

}

$result = Get-ODBC-Data

Write-Host "Statistic: " $result[0];

Write-Host "Message: " $result[0] ;

But I still don't know how to use it!

Where am I supposed to provide a username and a password?

Can you please provide me with the command to run on Powershell to run the script?

Or is there a better way to connect?

THANKS!

Upvotes: 3

Views: 15692

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123609

Where am I supposed to provide a username and a password?

You include them as UID= and PWD= in the connection string:

$connStr = @"
DSN=mssqlLocal64;
UID=scott;
PWD=tiger;
"@
$con = New-Object System.Data.Odbc.OdbcConnection $connStr
$con.Open()
$sql = "SELECT name, create_date FROM sys.tables ORDER BY name"
$cmd = New-Object System.Data.Odbc.OdbcCommand $sql, $con
$rdr = $cmd.ExecuteReader()
while ($rdr.Read())
{
    Write ("[{0}] -> {1}" -f $rdr["name"], $rdr["create_date"])
}
$rdr.Close()
$con.Close()

Upvotes: 6

Related Questions