大家好!
我带着一个卑微的问题来找你(请原谅我,我在PowerShell中相当好,但我的SQL技能是最小的…()
所以我的任务是写一个powershell脚本来导入数据(从一些csv文件到数据库),我取得了很好的进展,基于此(我大量修改了我的版本)。所有工作都很顺利,除了一个部分:当我试图插入值时(我创建了一种"映射文件")。将csv头映射到数据),我似乎不能在值部分使用创建的字符串。下面是我的代码:
这是我当前的powershell代码(忽略注释)
这是一个样本数据csv
这是我的映射文件我想要的是替换
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)'
);"
部分,例如使用如下方式生成的字符串:
但是,当我用$valueString替换长值时,我得到了这种类型的错误:
Incorrect syntax was encountered while parsing '$($'.
不确定,如果它重要,但我的PS是7.1
任何好的人谁可以给一个好的建议如何建立价值从我的文本文件…?
助教,f .
如前所述,将变量包装在单引号内将按照字面意思写入变量,因此您不会获得包含的值(7957
),而是获得像$($CSVLine.Numeric_counter)
这样的字符串。
我不做SQL很多,但我想我会改变你构建值插入的部分,像这样:
# demo, read the csv file in your example
$csv = Import-Csv D:Testtest.csv -Delimiter ';'
# demo, these are the headers (or better yet, the Property Names to use from the objects in the CSV) as ARRAY
# (you use `$headers = Get-Content -Path 'C:TempSQLImportingCSVsIntoSQLv1configheaders.txt'`)
$headers = 'Invoice_Status_Text','Invoice_Status','Dispute_Required_Text','Dispute_Required',
'Dispute_Resolved_Text','Dispute_Resolved','Sub_Account_Number','QTY','Date_of_Service',
'Service','Amount_of_Service','Total','Location','Dispute_Reason_Text','Dispute_Reason','Numeric_counter'
# capture formatted blocks of values for each row in the CSV
$AllValueStrings = $csv | ForEach-Object {
# get a list of values using propertynames you have in the $headers
$values = foreach ($propertyName in $headers) {
$value = $_.$propertyName
# output the VALUE to be captured in $values
# for SQL, single-quote the string type values. Numeric values without quotes
if ($value -match '^[d.]+$') { $value }
else { "'{0}'" -f $value }
}
# output the values for this row in the CSV
$values -join ",`r`n"
}
# $AllValueStrings will now have as many formatted values to use
# in the SQL as there are records (rows) in the csv
$AllValueStrings
使用你的例子,$AllValueStrings将产生
'Ready To Pay',
1,
'No',
2,
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
7957