Quantcast
Channel: Active questions tagged powershell-3.0 - Stack Overflow
Viewing all articles
Browse latest Browse all 122

Powershell Try/Catch Exception to SQL

$
0
0

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.


Viewing all articles
Browse latest Browse all 122

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>