【问题标题】:PowerShell Insert into SQL Server issuePowerShell 插入 SQL Server 问题
【发布时间】:2017-11-21 12:46:59
【问题描述】:

这是我正在使用的代码:

$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”时出现异常:“关键字‘is’附近的语法不正确。”
在行:10 字符:13
+ $rowsUpdated=$command2.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException

这次我错过了什么?

在这个 sn-p 之外定义和填充变量。

代码

$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); 

【问题讨论】:

  • 我的猜测是您需要检查您在 SQL 语句中扩展的 PowerShell 变量的值。错误似乎指向 SQL 语句,如果没有这些值,将很难排除故障。
  • 在杰夫所说的之上。您还添加了我没有看到在您的插入语句中使用的 sql 参数。我们无法为您猜到这一点。 $command2.CommandText 打印到控制台看起来像什么?
  • $SessionVal、$StartedVal、$StatusVal、$DescVal、$TargetVal、$SysDateVal、$MailVal 定义在哪里?
  • 您在插入语句中缺少单个环绕文本

标签: sql-server powershell


【解决方案1】:

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

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); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2013-06-02
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多