2014-03-03 141 views
0

我试图修改this script,以便将安装的更新插入到SQL Server数据库表中。将Microsoft更新插入到数据库中

$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更新,但它没有显示hotfixid和修补程序descriptien列有各行的唯一一个更新。

谢谢!

+0

我修正了我自己的问题。但事情我不能工作是每个更新都列在SQL不仅是第一个 – user22401

回答

0

在循环中执行INSERT。但是,我会建议您使用预准备语句,而不是通过字符串连接构建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服务器。我还怀疑有一种更有效的方式来处理准备好的语句,但我并不熟悉SQL Server。