views:

1378

answers:

2

I need to periodically query the event logs on a handful of servers and insert specific events into a Postgres table.

I am having trouble figuring out how I can insert data into a table via ODBC using PowerShell and/or VBScript. I'm reasonably familiar with both VBScript and PowerShell generally, and I can craft a SQL UPDATE statement that works, I'm just trying to tie the two together, which I've never done before.

I have the Postgres ODBC driver installed, I've configured a data source which tests OK.

Google isn't helping me thus far, can someone provide some pointers?

A: 

What part are you having trouble with? How far havve you got? Do you have a connection open? Do you know the syntax of the connection string?

Prepare a connection:

Set conn = Server.CreateObject("ADODB.Connection")
conn.Open dsn, dbuser, dbpass

insert:

insert = "insert into table (col1, col2) values (12, 'Example Record')"
conn.Execute insert
If conn.errors.Count > 0 Then
    Dim counter
    WScript.echo "Error during insert"
    For counter = 0 To conn.errors.Count
        WScript.echo "Error #" & DataConn.errors(counter).Number
        WScript.echo "  Description(" & DataConn.errors(counter).Description & ")"
    Next
Else
    WScript.echo "insert: ok"
End If

for completeness, query:

query = "select * from table where col1 = 7"
Set recordSet = conn.execute(query)
' result is an object of type ADODB.RecordSet

If you want powershell, try this post.
If you need to know the connection string, try connectionstrings.com.

Cheeso
A: 

Thanks for the response.

I used more Googling and eventually grokked enough ADO.NET to get it working, although it may not necessarily be "correct".

$DBConnectionString = "Driver={PostgreSQL UNICODE};Server=$DBIP;Port=$DBPort;Database=$DBName;Uid=$DBUser;Pwd=$DBPass;"

$DBConn = New-Object System.Data.Odbc.OdbcConnection
$DBConn.ConnectionString = $DBConnectionString

$DBCmd = $DBConn.CreateCommand()

[void]$DBCmd.Parameters.Add("@TimeStamp", [System.Data.Odbc.OdbcType]::varchar, 26)
[void]$DBCmd.Parameters.Add("@ErrorText", [System.Data.Odbc.OdbcType]::varchar, 4000)

$DBCmd.CommandText = "INSERT INTO errorinfo (errortime,xml) VALUES(?,?)"

$DBCmd.Connection.Open()

$DBCmd.Parameters["@TimeStamp"].Value = $TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")
$DBCmd.Parameters["@ErrorText"].Value = $ErrorText

[void]$DBCmd.ExecuteNonQuery()
Graeme Donaldson