【发布时间】:2021-08-08 12:39:24
【问题描述】:
嗨,Interwebz 的 Glorius 人!
我带着一个不起眼的问题来找你(请放轻松,我在 PowerShell 方面还算不错,但我的 SQL 技能很少……:()
因此,我的任务是编写一个 powershell 脚本来导入数据(从多个 csv 文件到数据库),并且基于this(我对我的版本进行了大量修改),我取得了不错的进展。除了一个部分之外,所有的工作都很顺利:当我尝试插入值时(我创建了一种“映射文件”来将 csv 标头映射到数据),我似乎无法在值部分使用创建的字符串。所以这就是我所拥有的:
This is my current code for powershell(忽略 cmets)
我想要的是替换
VALUES(
'$($CSVLine.Invoice_Status_Text)',
'$($CSVLine.Invoice_Status)',
'$($CSVLine.Dispute_Required_Text)',
'$($CSVLine.Dispute_Required)',
'$($CSVLine.Dispute_Resolved_Text)',
'$($CSVLine.Dispute_Resolved)',
'$($CSVLine.Sub_Account_Number)',
'$($CSVLine.QTY)',
'$($CSVLine.Date_of_Service)',
'$($CSVLine.Service)',
'$($CSVLine.Amount_of_Service)',
'$($CSVLine.Total)',
'$($CSVLine.Location)',
'$($CSVLine.Dispute_Reason_Text)',
'$($CSVLine.Dispute_Reason)',
'$($CSVLine.Numeric_counter)'
);"
Part, for example with a string generated this way:
但是当我用 $valueString 替换长的 - 老实说,无聊的类型 - 值时,我得到了这种类型的错误:
Incorrect syntax was encountered while parsing '$($'.
不确定是否重要,但我的 PS 是 7.1
任何好的人可以就如何从我的文本文件中构建值提出好的建议...?
Ta, F.
【问题讨论】:
-
尝试使用双引号 (
") 而不是单引号 (')。单引号取字面上的任何内容,而双引号插入变量。所以在你的函数中做$valuesString = foreach ($string in $headers) { '"{0}"' -f ($placeholder -replace '__replaceme__' , $string) } -
不确定我是否正确,但我为此更改了代码: $headers = Get-Content -Path 'C:\Temp\SQL\ImportingCSVsIntoSQLv1\config\headers.txt' $headersString = $headers -join ', ' $placeholder = '$($CSVLine.__replaceme__)' $valuesString = @() foreach ($headers 中的$string){ $value = '"{0}"' -f ($placeholder -replace 'replaceme' , $string) $valuesString += $value } $valuesString = $valuesString -join ', ' 这会导致:"$($CSVLine.Numeric_counter)", "$( $CSVLine.Invoice_Status_Text)" .... 但我仍然收到错误... :(
-
你说的SQL,是指SQL Server吗?一些 DBMS 产品附带一个实用程序,可以将 csv 文件读入表中。
标签: sql powershell