-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertTo-CsvOnDoubleNewline.ps1
More file actions
137 lines (105 loc) · 4.94 KB
/
Copy pathConvertTo-CsvOnDoubleNewline.ps1
File metadata and controls
137 lines (105 loc) · 4.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
function ConvertTo-CsvOnDoubleNewline {
<#
.SYNOPSIS
Converts a text file to CSV format by splitting on double newlines.
.DESCRIPTION
This function reads a text file and splits it into rows whenever two consecutive
newlines (blank lines) are encountered. Each group of lines between double newlines
becomes a row in the output CSV. The CSV is saved with the same name and location
as the input file with a .csv extension.
.PARAMETER InputPath
The path to the input text file to process.
.PARAMETER OutputPath
Optional. The path where the CSV file will be saved. If not specified,
the output will be saved in the same directory as the input file with a .csv extension.
.PARAMETER Force
If specified, overwrites the output file if it already exists.
.EXAMPLE
ConvertTo-CsvOnDoubleNewline -InputPath "C:\data\input.txt"
Reads C:\data\input.txt and creates C:\data\input.csv
.EXAMPLE
ConvertTo-CsvOnDoubleNewline -InputPath ".\data.txt" -OutputPath ".\output.csv" -Force
Reads data.txt and creates output.csv, overwriting if it exists.
.EXAMPLE
Get-ChildItem *.txt | ForEach-Object { ConvertTo-CsvOnDoubleNewline -InputPath $_.FullName }
Processes all .txt files in the current directory.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName", "Path")]
[ValidateScript({
if (Test-Path $_ -PathType Leaf) {
$true
} else {
throw "File '$_' does not exist."
}
})]
[string]$InputPath,
[Parameter(Mandatory=$false)]
[string]$OutputPath,
[Parameter(Mandatory=$false)]
[switch]$Force
)
Process {
try {
# Resolve the full path
$inputFile = Get-Item -Path $InputPath -ErrorAction Stop
# Determine output path
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
$outputFile = Join-Path -Path $inputFile.DirectoryName -ChildPath "$($inputFile.BaseName).csv"
} else {
$outputFile = $OutputPath
}
Write-Verbose "Reading input file: $($inputFile.FullName)"
# Read the entire file content
$content = Get-Content -Path $inputFile.FullName -Raw
# Split on double newlines (handles both Windows \r\n and Unix \n)
# This regex matches two or more consecutive newlines
$records = $content -split "(\r?\n){2,}" | Where-Object { $_.Trim() -ne "" }
Write-Verbose "Found $($records.Count) records"
if ($records.Count -eq 0) {
Write-Warning "No records found in the input file."
return
}
# Process each record into an object
$csvData = @()
$maxFields = 0
foreach ($record in $records) {
# Split each record into lines
$lines = $record -split "\r?\n" | Where-Object { $_.Trim() -ne "" }
# Track the maximum number of fields
if ($lines.Count -gt $maxFields) {
$maxFields = $lines.Count
}
$csvData += ,$lines
}
Write-Verbose "Maximum fields per record: $maxFields"
# Create objects with consistent property names
$objects = @()
for ($i = 0; $i -lt $csvData.Count; $i++) {
$obj = New-Object PSCustomObject
for ($j = 0; $j -lt $maxFields; $j++) {
$fieldName = "Field$($j + 1)"
$fieldValue = if ($j -lt $csvData[$i].Count) { $csvData[$i][$j] } else { "" }
$obj | Add-Member -MemberType NoteProperty -Name $fieldName -Value $fieldValue
}
$objects += $obj
}
# Check if output file exists
if ((Test-Path $outputFile) -and -not $Force) {
throw "Output file '$outputFile' already exists. Use -Force to overwrite."
}
# Export to CSV
$objects | Export-Csv -Path $outputFile -NoTypeInformation -Force:$Force
Write-Host "Successfully created CSV: $outputFile" -ForegroundColor Green
Write-Verbose "Exported $($objects.Count) rows with $maxFields columns"
# Return the output file info
Get-Item -Path $outputFile
}
catch {
Write-Error "Error processing file: $_"
throw
}
}
}