简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM