user2782999
user2782999

Reputation: 425

Powershell Try/Catch Exception to SQL

Hello I have a little problem regarding my error logging to SQL from powershell scripts.

function Invoke-Sqlcmd {
    param(
    [Parameter(Position=0, Mandatory=$true ,ValueFromPipeline = $false)] [string]$ServerInstance,
    [Parameter(Position=1, Mandatory=$true ,ValueFromPipeline = $false)] [string]$Database,
    [Parameter(Position=2, Mandatory=$false ,ValueFromPipeline = $false)] [string]$UserName,
    [Parameter(Position=3, Mandatory=$false ,ValueFromPipeline = $false)] [string]$Password,
    [Parameter(Position=4, Mandatory=$true ,ValueFromPipeline = $false)] [string]$Query,
    [Parameter(Position=5, Mandatory=$false ,ValueFromPipeline = $false)] [Int32]$QueryTimeout=30
    )

    $conn=new-object System.Data.SqlClient.SQLConnection
    if ($UserName -and $Password)

        { $conn.ConnectionString="Server={0};Database={1};User ID={2};Pwd={3}" -f $ServerInstance,$Database,$UserName,$Password }
    else
        { $conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $ServerInstance,$Database  }

    $conn.Open()
    $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
    $cmd.CommandTimeout=$QueryTimeout
    $ds=New-Object system.Data.DataSet
    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
    [void]$da.fill($ds)
    $conn.Close()
    $ds.Tables[0]
}
try {
    ThisCommandDoesNotExist
}
catch {
    $Exception = $_.Exception.Message
    Invoke-Sqlcmd -Serverinstance mysqlserver -Database Mydatabase -Query "Insert into MyTable Values (GetDate(),'$Exception')"
}

The error I receive is:

Invoke-Sqlcmd: Exception calling "Fill with "1" argument(s): "Incorrect syntax near 'ThisCommandDoesNotExist'

I suppose it has something do to with the single quotes, I am no SQL expert. But I have tried doing a replace on all the "'" and "," and "." but still the same error is thrown.

Upvotes: 1

Views: 2942

Answers (3)

Nico Botes
Nico Botes

Reputation: 41

This was a killer, 3.43hours of my life I will never reclaim...

The fix for me:

'$($ErrorMessage -replace "'", "''")'

from the call in the Catch-part (you can see from comments I tried a couple of things :) ):

 catch{
        #do something on the catch
        #$errorvarclean = $error -replace '[#?\{]','_A'
        #$string_err = $_ | Out-String
        #$string_err = $_ | Format-List * -Force | Out-String
        #Write-Host($string_err)
        LogToTable-SQLConnectionTestResults $row.SrvLoginName $row.ServerName $row.DatabaseName $row.program_name "0" $Error[0]
        #$Error[0]
        #$_.Exception.Message
        #Write-Host($error)
        #Write-Host($errorvarclean)
    }

Good luck folks!

Upvotes: 0

todd
todd

Reputation: 11

You are correct, the single-quotes makes powershell treat your $variable as a string.

You can escape powershell special characters by using the backtick `.

Upvotes: 1

user2782999
user2782999

Reputation: 425

Found the solution myself. At last it work when i did replace on .,:=

Upvotes: 0

Related Questions