簡體   English   中英

我正在嘗試將兩個 csv 文件與 powershell 中的不同列合並,接收錯誤

[英]I am trying to merge two csv files with different columns in powershell, receiving error

我有兩個 csv 文件。 假設我在第一個文件中有三列,分別是名稱、ID 和電話,第二個文件是地址和位置。 我正在嘗試使用以下腳本合並它們:

$dir = ".\csvs"

foreach ($csv in (Get-ChildItem "$dir\*.csv"))
{
    Import-Csv $csv | Export-Csv .\merged.csv -NoTypeInformation -Append
}

但我收到以下錯誤:

Export-Csv : Cannot append CSV content to the following file: .\merged.csv. The appended object does not have a
property that corresponds to the following column: . To continue with mismatched properties, add the -Force parameter,
and then retry the command.

這個錯誤想表達什么? 新文件為空。

您希望做的基本上是“加入”。 無論是 CSV、CLIXML、JSON 還是任何一組對象,您都可以通過多種方式構建基本連接。

假設您沒有可以加入的“關鍵”行,並且您只是按順序加入每一行。

# Create a hashtable or [Ordered] hashtable to keep track of each file
$fileData  = [Ordered]@{}
# We'll need to know the maximum number of rows, so set it to zero.
$MaxRowCount = 0 
# Walk over each file
foreach ($csvFile in (Get-ChildItem "$dir\*.csv")) {
   # Import the CSV, using the array operator force it into a list.
   $csvData = @(Import-Csv $csvFile)
   # Put it into our table
   $fileData[$csvFile] = $csvData
   if ($fileData[$csvFile].Length -gt $MaxRowCount) {
      $maxRowCount = $fileData[$csvFile].Length 
   }   
}

# Now, we need to go row-by-row and join our data
# In PowerShell, you can assign the results of a for statement.
# So we can just walk thru our loop and let it populate the data
# (though, once again, we're using to array operator to force it into an array)
$joinedData =
@(for ($rowNumber = 0 ; $rowNumber -lt $maxRowCount; $rowNumber++) {
    # Create an ordered hashtable for the new data
    $newRow = [Ordered]@{}
    # Walk thru each file
    foreach ($filePath in $fileData.Keys) {
       # and get the row from the file.
       $fileRow = $fileData[$filePath][$rowNumber]
       # Every object in PowerShell wrapped in a .PSObject
       # this lets us walk the properties of each row
       foreach ($prop in $fileRow.PSObject.Properties) {
           # copy the data into the new output
           # (the last file will 'win' when property names collide)
           $newRow[$prop.Name] = $prop.Value       
       }
    }

    # now, we turn our row into an object
    [PSCustomObject]$newRow
})

$joinedData | Export-Csv .\Joined.csv

如果您想使用鍵屬性來連接行,請澄清問題,我可以提供類似的答案(您將逐個鍵值,而不是逐行)。

同樣,對象不必來自 CSV 文件。 您可以輕松地將 Import-CSV 替換為 Import-CliXml,或者說,Import-Excel(來自模塊 ImportExcel)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM