Get CsvData - PPOSHGROUP/PPoShTools GitHub Wiki
Reads CSV file using specific encoding and running optional Validation and Transformation rules.
Get-CsvData [-CsvPath] <String> [-CsvDelimiter] <String> [[-CustomEncoding]
<String>] [[-CsvValidationRules] <ScriptBlock>] [[-CsvTransformRules]
<ScriptBlock>] [<CommonParameters>]
After CSV file is read, Validation phase is run, that is for each row $CsvValidationRules scriptblock is invoked, which returns array of string: - if the array is empty it is assumed the row is valid. - if the array is non-empty, it is assumed the row is invalid and the strings will be displayed after the Validation phase. Then, Transformation phase is run, that is for each row $CsvTransformationRules scriptblock is invoked, which returns a hashtable that is then passed as a final result.
Path to input CSV file.
- PipelineInput: false
- Required: true
CSV delimiter in input CSV file.
- PipelineInput: false
- Required: true
If specified, CSV file will be first reencoded to UTF-8 (to a temporary file).
- PipelineInput: false
- Required: false
A scriptblock invoked for each row that accepts [PSCustomObject]$CsvRow and [int]$CsvRowNum. It returns array of string.
- PipelineInput: false
- Required: false
A scriptblock ivoked for each row that accepts [PSCustomObject]$CsvRow and [int]$CsvRowNum. It returns hashtable.
- PipelineInput: false
- Required: false
function Get-ValidationRules {
[CmdletBinding()] [OutputType([string[]])] param( [Parameter(Mandatory = $true)] [PSCustomObject] $CsvRow,
[Parameter(Mandatory = $true)]
[int]
$CsvRowNum
)
$errors = @()
$errors += Test-ColumnIsValid -Row $CsvRow -ColumnName 'Login' -NonEmpty -NotContains '?', ' '
$errors += Test-ColumnIsValid -Row $CsvRow -ColumnName 'Name' -NonEmpty -NotContains '?'
$errors += Test-ColumnIsValid -Row $CsvRow -ColumnName 'First Name' -NonEmpty -NotContains '?', ' '
$errors += Test-ColumnIsValid -Row $CsvRow -ColumnName 'Last Name' -NonEmpty -NotContains '?'
return $errors
}
function Get-TransformRules {
[CmdletBinding()]
[OutputType([hashtable])]
param(
[Parameter(Mandatory = $true)]
[PSCustomObject]
$CsvRow,
[Parameter(Mandatory = $true)]
[int]
$CsvRowNum
)
$result = @{
Name = Remove-DiacriticChars -String (($CsvRow.'Name'))
FirstName = Remove-DiacriticChars -String (($CsvRow.'First Name'))
LastName = Remove-DiacriticChars -String (($CsvRow.'Last Name'))
Login = $CsvRow.Login
}
return $result
}
$csvParams = @{ CsvPath = 'test.csv' CsvDelimiter = ';' CsvValidationRules = (Get-Command -Name Get-ValidationRules).ScriptBlock CsvTransformRules = (Get-Command -Name Get-TransformRules).ScriptBlock CustomEncoding = 'Windows-1250' } $employeeData = Get-CsvData @csvParams