简体   繁体   English

Powershell SQL的try / catch异常

[英]Powershell Try/Catch Exception to SQL

Hello I have a little problem regarding my error logging to SQL from powershell scripts. 您好,我有一些关于从Powershell脚本记录到SQL的错误的问题。

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. 我想它与单引号有关,我不是SQL专家。 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. 没错,单引号使powershell将$ variable视为字符串。

You can escape powershell special characters by using the backtick ` . 您可以使用反引号`来转义Powershell特殊字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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