PowerShell插入SQL Server问题

时间:2017-11-21 12:47:00

标签: sql-server powershell

这是我正在使用的代码:

$command2 = New-Object System.Data.SqlClient.SqlCommand
#$MySql2="Invoke-sql INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES ($SessionVal, $StartedVal, $StatusVal, $DescVal, $TargetVal, $SysDateVal, $MailVal); "

$command2.CommandText = "INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES ($SessionVal, $StartedVal, $StatusVal, $DescVal, $TargetVal, $SysDateVal, $MailVal); "
$command2.Connection = $connect2
$command2.Parameters.AddWithValue("@server", $_.server) | Out-Null
$command2.Parameters.AddWithValue("@instance", $_.instance) | Out-Null

$rowsUpdated = $command2.ExecuteNonQuery()

Write-Output "Updating SQL Database; Adding record for "$SessionVal
Write-Output " "
$connect2.Close()

当我运行它时,我收到此错误:

  

使用“0”参数调用“ExecuteNonQuery”的异常:“关键字'附近的语法不正确'是'。”
  在行:10 char:13
  + $ rowsUpdated = $ command2.ExecuteNonQuery()
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   + CategoryInfo:NotSpecified:(:) [],MethodInvocationException
  + FullyQualifiedErrorId:SqlException

这次我错过了什么?

在此代码段之外定义并填充变量。

代码

$command2.CommandText = INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES (this is a test, 2017-11-17T07:00:01.418178+00:00, processing, name of site, address of site, 20/11/2017 15:57, 0); 

1 个答案:

答案 0 :(得分:0)

您的插入语句应如下所示。您缺少文字周围的单引号:

INSERT INTO acubdb.scans 
            (sessionid, 
             started, 
             status, 
             description, 
             target, 
             systime, 
             mailed) 
VALUES      ('this is a test', 
             '2017-11-17T07:00:01.418178+00:00', 
             'processing', 
             'name of site', 
             'address of site', 
             '20/11/2017 15:57', 
             0);