0

我在 SQL Server 2016 Express 中创建了一个测试数据库,它包含 1 个标有drivers.

我使用 PowerShell 对已安装的驱动程序执行 ciminstance 查询,然后将这些值插入到测试数据库驱动程序表中。(插入按预期工作)我遇到的问题是尝试更新驱动程序表,只有最后一个对象被插入数据库 40 次(即从 ciminstance 查询返回了多少驱动程序)。我创建了 2 个 PowerShell 脚本

  1. 插入值
  2. 更新值

难倒!

$database = 'test'
$server = 'groga\sqlExpress'
$table = 'dbo.Driver'
$SQLServer = "groga\sqlExpress"
$SQLDBName = "test"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = 
$SQLDBName; Integrated Security = True"

$SqlConnection.Open()
$today = Get-Date

$drivers = gcim win32_pnpsigneddriver -Property * 
$model = gcim win32_computersystem -Property *
foreach($driver in $drivers)
{
if(!($driver.Description -match "Generic") -and $driver.Manufacturer -
notmatch 'Microsoft|Standard|Generic' -and $driver.DriverDate -ne $null)
{
    $count = New-Object psobject -Property @{

        'Date' = $driver.DriverDate
        'Manufacturer' = $driver.Manufacturer
        'Version' = $driver.DriverVersion
        'PackageID' = "0"
        'SKU' = $model.SystemSKUNumber
        'Model' = $model.Model
        'Today' = $today} 

$col1 = $count.Date
$col2 = $count.Manufacturer
$col3 = $count.Version
$col4 = $count.PackageID
$col5 = $count.SKU
$col6 = $count.Model
$col7 = $count.Today

$update = @"
   UPDATE $table
   SET [Date]='$col1',
     [Manufacturer]='$col2',
     [Version]='$col3',
     [PackageID]='$col4',
     [SKU]='$col5',
     [Model]='$col6',
     [Today]='$col7'     
"@

  $dbwrite = $SqlConnection.CreateCommand()
  $dbwrite.CommandText = $update
  $dbwrite.ExecuteNonQuery() 
  }

}

$Sqlconnection.Close()
4

1 回答 1

0

UPDATE 语句将应用于查询匹配的所有行。因此,您的脚本正在做的是将表中的所有行设置为驱动程序的信息,然后对整个列表执行相同的操作。

您将需要确定唯一标识每个驱动程序的字段,然后将您的查询过滤到该字段。查看示例驱动程序信息,这可能是日期、制造商、设备名称(您需要添加到架构中的内容)、DriverVersion。

仅包含日期、制造商、驱动程序版本的示例:

$update = @"
   UPDATE $table
   SET [PackageID] = '$col4'
     [SKU]='$col5',
     [Model]='$col6',
     [Today]='$col7'     
     WHERE [Date] = '$col1' AND [Manufacturer]='$col2' AND [Version]='$col3' 
"@
于 2017-06-19T01:21:06.137 回答