2017-06-18 91 views
0

我在SQL Server 2016 Express中創建了一個測試數據庫,它包含一個標記爲drivers的表。無法從powershell更新SQL Server表

我使用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() 
+2

更新記錄時要小心。如果您省略'WHERE'子句,**所有**記錄將被更新! – JosefZ

+0

謝謝JosefZ,我正在嘗試更新所有記錄。 – grunzer

回答

0

UPDATE語句將應用於查詢所匹配的所有行。因此,你的腳本正在做的是將表中的所有行設置爲驅動程序的信息,然後對整個列表進行相同操作。

您需要確定唯一標識每個驅動程序的字段,然後將查詢過濾到該字段。看看示例驅動程序信息,這可能是日期,製造商,設備名稱(您需要添加到您的模式),DriverVersion。

實例只有日期,生產廠家,DriverVersion:

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

謝謝亞歷克,我會重寫更新查詢和測試 – grunzer