脚本PowerShell使用csv更新SQL Server

时间:2018-12-12 21:33:08

标签: powershell csv

我正在尝试创建一个脚本,该脚本允许从具有不同名称的多个CSV文件更新我的SQL Server数据库,例如:

LOHNSJSHM_details.csv
ZULTNQNIW_details.csv
...

数据更新后,必须自动删除文件。

这就是我开始做的事情:

If ((Get-PSSnapin | where {$_.Name -match "SqlServerCmdletSnapin100"}) -eq $null)
{
  Add-PSSnapin SqlServerCmdletSnapin100
}

If ((Get-PSSnapin | where {$_.Name -match "SqlServerProviderSnapin100"}) -eq $null)
{
  Add-PSSnapin SqlServerProviderSnapin100
}

$sql_instance_name = 'ServerSQL01\LAB'
$db_name = 'testdb'

$impcsv = ".\Example.csv"

$data = import-csv $impcsv

$count = 1

foreach($i in $data){

$reference = $i.reference
$quantity = $i.quantite

$query = "UPDATE dbo.F_ARTSTOCK (reference,quantity)
          SET quantity = '$quantity'
          WHERE reference = '$reference'"

$impcsv = invoke-sqlcmd -Database $db_name -Query $query  -serverinstance $sql_instance_name 

write-host "Processing row ..........$count" -foregroundcolor green

$count  = $count + 1

}

我的文件有2列(参考,数量),我必须根据CSV每一行的参考提取量来更新SAGE表

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

If ((Get-PSSnapin | where {$_.Name -match "SqlServerCmdletSnapin100"}) -eq $null)
{
  Add-PSSnapin SqlServerCmdletSnapin100
}

If ((Get-PSSnapin | where {$_.Name -match "SqlServerProviderSnapin100"}) -eq $null)
{
  Add-PSSnapin SqlServerProviderSnapin100
}

$sql_instance_name = 'ServerSQL01\LAB'
$db_name = 'testdb'

$csv_folder = 'C:\temp'
$csv_completed_folder = 'C:\done'

# assuming only csv-files you want to import are located in $csv_folder
$csv_files = Get-Childitem -Path $csv_folder -Filter '*.csv'

foreach($file in $csv_files) {
    $impcsv = $file.FullName
    write-host "Processing file ..........$impcsv" -foregroundcolor green
    $data = import-csv $impcsv

    $count = 1

    foreach($i in $data) {

    $reference = $i.reference
    $quantity = $i.quantite

    $query = "UPDATE dbo.F_ARTSTOCK (reference,quantity)
              SET quantity = '$quantity'
              WHERE reference = '$reference'"

    $impcsv = invoke-sqlcmd -Database $db_name -Query $query  -serverinstance $sql_instance_name 

    write-host "Processing row ..........$count" -foregroundcolor green

    $count  = $count + 1

    }
}