我有以下代碼查詢MSSQL服務器數據庫,然後將結果與CSV進行比較,CSV中與數據庫中對應行不匹配的任何行都添加到新的CSV,創建一個只包含更改行的CSV,並丟棄未更改的CSV。問題在powershell中將數組導出爲CSV
$priceCSV = Import-Csv C:\Users\user\Desktop\pricedelta\Products.csv
$newpriceCSV = @(,@("SKU","BrandName","ID","Name","1stCheapestDistributorName","1stCheapestDistributorPrice","1stCheapestDistributorStock","1stCheapestDistributorProductName","1stCheapestDistributorDeliveryCost","2ndCheapestDistributorName","2ndCheapestDistributorPrice","2ndCheapestDistributorStock","2ndCheapestDistributorProductName","2ndCheapestDistributorDeliveryCost","3rdCheapestDistributorName","3rdCheapestDistributorPrice","3rdCheapestDistributorStock","3rdCheapestDistributorProductName","3rdCheapestDistributorDeliveryCost","4thCheapestDistributorName","4thCheapestDistributorPrice","4thCheapestDistributorStock","4thCheapestDistributorProductName","4thCheapestDistributorDeliveryCost","5thCheapestDistributorName","5thCheapestDistributorPrice","5thCheapestDistributorStock","5thCheapestDistributorProductName","5thCheapestDistributorDeliveryCost","DescriptionType"))
####
#Checks for changed rows are here
####
$NewArray = @()
$names = @("SKU","BrandName","ID","Name","1stCheapestDistributorName","1stCheapestDistributorPrice","1stCheapestDistributorStock","1stCheapestDistributorProductName","1stCheapestDistributorDeliveryCost","2ndCheapestDistributorName","2ndCheapestDistributorPrice","2ndCheapestDistributorStock","2ndCheapestDistributorProductName","2ndCheapestDistributorDeliveryCost","3rdCheapestDistributorName","3rdCheapestDistributorPrice","3rdCheapestDistributorStock","3rdCheapestDistributorProductName","3rdCheapestDistributorDeliveryCost","4thCheapestDistributorName","4thCheapestDistributorPrice","4thCheapestDistributorStock","4thCheapestDistributorProductName","4thCheapestDistributorDeliveryCost","5thCheapestDistributorName","5thCheapestDistributorPrice","5thCheapestDistributorStock","5thCheapestDistributorProductName","5thCheapestDistributorDeliveryCost","DescriptionType")
$skip = 1
foreach($row in $newpriceCSV)
{
if($skip -eq 1){
$skip = 0
continue
}
$obj = new-object PSObject
for ($i=0;$i -lt 30; $i++){
$obj | add-member -membertype NoteProperty -name $names[$i] -value $row[$i]
}
$NewArray+=$obj
$obj=$null
}
$NewArray
$NewArray | Export-Csv -path "C:\Users\user\Desktop\pricedelta\NewProducts.csv" -NoTypeInformation -Encoding Unicode
數據庫查詢和支票和其他一切工作正常,但是當我嘗試將結果導出爲CSV我碰到了幾個不同的問題取決於我試試。
如果我只是嘗試導出-CSV $ newpriceCSV然後我得到的第一線和第二線了一堆廢話,然後一個逗號的每一行後順序,以類似的東西如下所示:http://sharepoint-community.net/profiles/blogs/powershell-from-an-array-to-comma-separated-file-csv-via-the#
試圖如圖所示的代碼相同的鏈接上找到了方法後,我得到以下錯誤:
Unable to index into an object of type System.Management.Automation.PSObject
該行:
$obj | add-member -membertype NoteProperty -name $names[$i] -value $row[$i]#
真的卡在哪裏可以從這裏,任何幫助表示讚賞
顯然,真正的'$ newpriceCSV'不包含數組,這是錯誤消息說什麼。使用PowerShell ISE在循環內設置一個斷點並計算'$ row.GetType()'以及'$ row | gm'此外,你的代碼非常低效,切換到使用'foreach'作爲表達式來自動生成數組和'[PSCustomObject] $ hashtable'方法而不是添加成員。 – wOxxOm