Last active
July 27, 2018 20:21
-
-
Save auberginehill/f278871a33f48fe07c522cba4a9a63e8 to your computer and use it in GitHub Desktop.
Appends CSV-files with Windows PowerShell v2.0, adds two custom extra columns to the merged file & replaces an expression inside the outputted CSV-file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Append-Csv.ps1 | |
#> | |
# The directory name contains at least one underscore in its name, and the first part | |
# is used in the outputted filename as a denominator ($directory = "denominator"). | |
# Note: UTF8 encoding in source files, perhaps? (for special characters et al.) | |
$path = "$env:USERPROFILE\Documents\denominator_split_files" | |
$directory = (Split-Path $path -Leaf).Split("_")[0] | |
$csv_file = "$path\merged_csvfile_$directory.csv" | |
$temp_file = "$path\merged_csvfile_temp_$directory.csv" | |
$list = Get-ChildItem -Path $path -Filter *.csv | |
If (($list.Count) -ge 2) { | |
"Merging $($list.Count) CSV-files." | |
} ElseIf (($list.Count) -eq 1) { | |
Return "Found one CSV-file - didn't merge." | |
} Else { | |
Return "Didn't find any CSV-files." | |
} # Else (If $list.Count) | |
ForEach ($item in $list) { | |
# Add columns "Type" (with values "original filename without the file-extension") and | |
# "Source" to the appended CSV-files and merge the files. | |
# Note: Append parameter of Export-Csv was introduced in PowerShell 3.0. | |
# $images_selection | Export-Csv $logfile_path -Delimiter ';' -NoTypeInformation -Encoding UTF8 -Append | |
Import-Csv $item.FullName -Header "longitude","latitude","Direction","ID" | | |
Select-Object *,@{ Label='Type'; Expression={"$($item.BaseName)"} },@{ Label='Source'; Expression={"scdb"} } | | |
ConvertTo-Csv -Delimiter ';' -NoTypeInformation | Select-Object -Skip 1 | | |
Out-File -FilePath $temp_file -Append -Encoding UTF8 | |
} # ForEach | |
Import-Csv "$temp_file" -Delimiter ';' -Header "longitude","latitude","Direction","ID","Type","Source" | | |
Export-Csv "$csv_file" -Delimiter ';' -NoTypeInformation -Encoding UTF8 | |
Remove-Item $temp_file -Force | |
# Replace an expression in the similar manner as "Find and Replace" | |
(Get-Content $csv_file) | ForEach-Object { $_ -replace ('-]',']') } | Out-File -FilePath $csv_file -Force -Encoding UTF8 |
Author
auberginehill
commented
Jul 27, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment