-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_console_table.ps1
More file actions
256 lines (228 loc) · 7.89 KB
/
csv_console_table.ps1
File metadata and controls
256 lines (228 loc) · 7.89 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<#
.SYNOPSIS
Analyzes CSV files and creates a column type schema dynamically.
.DESCRIPTION
Processes CSV files to identify column types and validates data against the schema.
Print snapshot of data and schema in console table format.
.EXAMPLE
.\csv_console_table.ps1 .\filename.csv
.NOTES
Author: /* (c) 2025 G.E. Eidsness */
#>
param(
[string]$DefaultFile = "default.csv",
[ValidateRange(1,1000)][int]$rowLimit = 10
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Check if PowerShell version is 7.0 or higher
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Host "This script requires PowerShell 7.0 or higher."
exit 1
}
# Define column types enum
enum ColumnType {
Null
String
Int
Float
Bool
}
# Function to get column types from a row
function Check-CSVRow-EmptyOrWhitespace {
[CmdletBinding()]
param (
[string[]]$row
)
foreach ($column in $row) {
# Trim leading and trailing whitespace
$trimmedColumn = $column.Trim()
# Enhanced regex to match empty, whitespace-only fields, or null values (case insensitive)
if ($trimmedColumn -match '^(?:["' + [char]39 + '])?\s*(?:["' + [char]39 + '])?$' -or
$trimmedColumn -imatch '^null$') {
return $true
}
}
return $false
}
# Updated function to validate data against schema
function Get-ColumnTypes {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string[]]$row
)
# Check if the row contains any empty or whitespace-only values
if (Check-CSVRow-EmptyOrWhitespace -row $row) {
Write-Warning "Error: First row cannot contain empty or whitespace-only values to determine column types."
exit 1
}
$columnTypes = @()
foreach ($item in $row) {
$item = $item.Trim()
if ($item -imatch '^\d+\.\d+$') {
$columnTypes += [ColumnType]::Float
} elseif ($item -imatch '^\d+$') {
$columnTypes += [ColumnType]::Int
} elseif ($item -imatch '^(true|false)$') {
$columnTypes += [ColumnType]::Bool
} elseif ([string]::IsNullOrWhiteSpace($item) -or $item -imatch '^null$|^NULL$') {
$columnTypes += [ColumnType]::Null
} else {
$columnTypes += [ColumnType]::String
}
}
return $columnTypes
}
# Function to colorize null values (unused)
function ColorizeNull($value) {
if ($value -imatch '^null$|^NULL$') {
return "`e[31m$($value)`e[0m" # Red color
}
return $value
}
function Test-DataAgainstSchema {
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string[]]$rows,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ColumnType[]]$schema
)
$validRows = @()
$errors = $false
foreach ($row in $rows) {
$items = $row.Split(",")
$isValid = $true
if ($items.Count -ne $schema.Count) {
Write-Warning "Row '$row' has invalid column count"
$isValid = $false
$errors = $true
continue
}
for ($i = 0; $i -lt $items.Count; $i++) {
$item = $items[$i].Trim()
switch ($schema[$i]) {
"Null" {
if (-not ([string]::IsNullOrWhiteSpace($item) -or $item -imatch '^null$|^NULL$')) {
$isValid = $false
$errors = $true
Write-Warning "Row '$row' expected Null in column $($i + 1) but found '$item'"
break
}
}
"Int" {
if (-not ($item -match '^\d+$')) {
$isValid = $false
}
}
"Float" {
if (-not ($item -match '^\d+\.\d+$')) {
$isValid = $false
}
}
"Bool" {
if (-not ($item -imatch '^(true|false)$')) {
$isValid = $false
}
}
"String" {
# Strings are accepted as-is
}
}
if (-not $isValid) {
Write-Warning "Row '$row' does not match schema at column $($i + 1)"
$errors = $true
break
}
}
if ($isValid) {
$validRows += $row
}
}
return @{ ValidRows = $validRows; HasErrors = $errors }
}
function TruncateString($str, $maxLength) {
if ($str.Length -gt $maxLength) {
return $str.Substring(0, $maxLength) + "..."
}
return $str
}
# Main script section
try {
$inputFile = ($args.Count -gt 0) ? $args[0] : $DefaultFile
# Add CSV extension validation
if (-not ($inputFile -match '\.csv$')) {
Write-Error "Input file must have a .csv extension"
exit 4
}
# Add file existence check
if (-not (Test-Path $inputFile)) {
Write-Error "CSV file '$inputFile' does not exist."
exit 2
}
try {
$csvContent = Get-Content $inputFile -ErrorAction Stop | Select-Object -First $rowLimit
} catch [System.IO.IOException] {
Write-Error "File access error: $_"
exit 3
}
# Check if the CSV file is empty
if ($csvContent.Count -eq 0) {
Write-Error "CSV file is empty."
exit 1
}
# Remove empty lines
$csvContent = $csvContent | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
$firstRow = $csvContent[0]
$firstRowItems = $firstRow -split ','
# Check for empty fields in the first row
if (Check-CSVRow-EmptyOrWhitespace -row $firstRowItems) {
Write-Warning "Error: First row cannot contain empty or whitespace-only values to determine column types."
exit 1
}
$colTypes = Get-ColumnTypes $firstRowItems
$colCount = $firstRowItems.Count
# Create unique headers with suffixes for duplicates
$headerCounts = @{}
$dynHeaders = 1..$colCount | ForEach-Object {
$type = $colTypes[$_-1]
if ($headerCounts.ContainsKey($type)) {
$headerCounts[$type] += 1
"$type$($headerCounts[$type])"
} else {
$headerCounts[$type] = 1
"$type"
}
}
# Validate data rows against schema
$validationResult = Test-DataAgainstSchema -rows $csvContent -schema $colTypes
$validRows = $validationResult.ValidRows
$hasErrors = $validationResult.HasErrors
if ($hasErrors -or $validRows.Count -eq 0) {
Write-Host "CSV data contains errors. Please check the warnings above."
exit 0
} else {
# Convert valid data rows to CSV format with dynamic headers
$csvString = $validRows -join "`n"
$csv = $csvString | ConvertFrom-Csv -Header $dynHeaders
# Process CSV content and store the result in $tableData
$tableData = $csv | ForEach-Object {
$newObject = [ordered]@{}
$_.PSObject.Properties | ForEach-Object {
$value = if ($_.Value -is [string]) { TruncateString $_.Value 40 } else { $_.Value }
$newObject[$_.Name] = $value
}
New-Object PSObject -Property $newObject
}
# Output $tableData to terminal | AND to file.txt
$tableData | Format-Table -AutoSize | Tee-Object -FilePath "output.txt" -Encoding UTF8
}
} catch {
Write-Error "Usage: $($MyInvocation.MyCommand.Name) <csv_file_path>"
exit 1
}