Overwriting CSV in PowerShell
I have a CSV document that is of the following structure
Headers
Path,Publish,Hashlist,Package
Content Entries
C:\packages\word.docx, 10:14:17 on 17-08-2011, C:\packages\word.hash, C:\packages\word.zip
Now, I will have multiple lines of entries, but I only want to maintain one entry per path at a given time. So when I add a new entry for C:\packages\word.docx, I want to find and delete the line above. I can append the .CSV no problem in PowerShell, but am unsure how to identify the line base开发者_StackOverflow中文版d on the filepath, and remove/overwrite it.
Something like this maybe:
$csv = import-csv test.csv
$tobeupdated = $csv | ?{$_.Path -eq "pathyouarecurrentlyprocessing"}
if($tobeupdated){
#update
$tobeupdated.Publish = "blah blah"
} else{
#add new
$tobeupdated = New-Object Object
$tobeupdated | Add-Member -type NoteProperty -name Path -value "c:\something.docx"
$tobeupdated | Add-Member -type NoteProperty -name Publish -value "10:14:17 on 17-08-2011"
$tobeupdated | Add-Member -type NoteProperty -name Hashlist -value "C:\packages\word.hash"
$tobeupdated | Add-Member -type NoteProperty -name Package -value "C:\packages\word.zip"
$csv += $tobeupdated
}
$csv | export-csv test.csv -notype
The update part maybe tricky based on what you are doing. So it will be helpful if you give some code on what you are doing.
This is what I use for updating CSV files. One nice thing about it is that all of the CSV entries don't need to be filtered for every record added/updated. It uses a HashTable to store the collection of CSV records.
function Update-MyCSV {
param(
[parameter(ValueFromPipeline=$true)]
$entry,
$csvPath
)
begin {
$csv = @{}
if(Test-Path $csvPath) {
# Import CSV and add to a HashTable
Import-Csv -Path $csvPath | foreach {$csv["$($_.Path)"] = $_}
}
}
process {
# Replaces existing entries and adds nonexisting
$csv[$entry.Path] = $entry
}
end {
# Export to CSV
$csv.Values | Export-Csv -Path C:\temp\my.csv -NoTypeInformation
}
}
function New-CsvEntry {
param(
$path,
$publish,
$hashlist,
$package
)
New-Object Object|
Add-Member -type NoteProperty -Name Path -Value $path -PassThru |
Add-Member -type NoteProperty -Name Publish -value $publish -PassThru |
Add-Member -type NoteProperty -Name Hashlist -value $hashlist -PassThru |
Add-Member -type NoteProperty -Name Package -value $package -PassThru
}
# Create new CSV
$entries = @(0..9| foreach {New-CsvEntry "C:\packages\word$_.docx" "10:14:1$_ on 17-08-2011" "C:\packages\word$_.hash" "C:\packages\word$_.zip"})
$entries| Update-MyCSV -csvPath C:\temp\my.csv
# Update some CSV records, and create some new
$newEntries = @(7..12| foreach {New-CsvEntry "C:\packages\word$_.docx" "10:14:1$_ on 17-08-2011" "C:\packages\new$_.hash" "C:\packages\new$_.zip"})
$newEntries| Update-MyCSV -csvPath C:\temp\my.csv
精彩评论