Sql 将Microsoft更新插入数据库

Sql 将Microsoft更新插入数据库,sql,powershell,updates,Sql,Powershell,Updates,我正在尝试修改,以便它将已安装的更新插入到SQL Server数据库表中 $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Data Source=sqlserver; Initial Catalog=updates; Integrated Security=SSPI;" $conn.Open() $cmd = New-Object System.Data.SqlClient.Sq

我正在尝试修改,以便它将已安装的更新插入到SQL Server数据库表中

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Data Source=sqlserver; Initial Catalog=updates; Integrated Security=SSPI;"

$conn.Open()

$cmd = New-Object System.Data.SqlClient.SqlCommand 
$cmd.Connection = $conn
$cmd = $conn.CreateCommand()
$wu = new-object -com “Microsoft.Update.Searcher”
$totalupdates = $wu.GetTotalHistoryCount()
$all = $wu.QueryHistory(0,$totalupdates)

$OutputCollection=  @()
Foreach ($update in $all){
 $Regex = “KB\d*”
$KB = $string | Select-String -Pattern $regex | Select-Object { $_.Matches }
$output = New-Object -TypeName PSobject
$output | add-member NoteProperty “HotFix ID” -value $KB.‘ $_.Matches ‘.Value
  $output | add-member NoteProperty “Title” -value $string
$OutputCollection += $output
 $cmd.CommandText += "INSERT INTO dbo.updates (hotfixid, hotfixdescription) VALUES ('$($kb.'$_.Matches'.Value)', ('$($string)'))"
}

$cmd.ExecuteNonQuery()
$conn.close()
目前,我在sql server中获得了正确的更新行数,但它没有显示hotfix ID,并且在hotfix descriptien列中,所有行中只有一个更新


谢谢

在循环内插入。但是,我建议您使用准备好的语句,而不是通过字符串连接来构建SQL语句。此外,当您不在任何地方使用时,无需构建
$OutputCollection
对象

像这样的方法应该会奏效:

...
$wu.QueryHistory(0, $totalupdates) | % {
  $KB = $_.Title | ? { $_ -match '(KB\d+)' } | % { $matches[1] }

  $cmd = $conn.CreateCommand()
  $cmd.CommandText = "INSERT INTO dbo.updates (hotfixid, hotfixdescription) " +
                     "VALUES (@id, @descr)"
  $cmd.Parameters.AddWithValue("@id", $KB)
  $cmd.Parameters.AddWithValue("@descr", $_.Title)
  $cmd.Prepare()
  $cmd.ExecuteNonQuery()
}
...

但未经测试,因为我手头没有SQL Server。我还怀疑有一种更有效的方法来处理准备好的语句,但我对SQL Server不太熟悉。

hotfixid我自己解决了。但我无法做到的是,每个更新都列在sql中,而不仅仅是第一个更新