Skip to content

Instantly share code, notes, and snippets.

@powercode
Last active August 21, 2023 14:58
Show Gist options
  • Save powercode/19eeb7c65e7542f4f221d54bb487307a to your computer and use it in GitHub Desktop.
Save powercode/19eeb7c65e7542f4f221d54bb487307a to your computer and use it in GitHub Desktop.
Automatic generation of a class to store data from import-csv
function New-TypeDefinitionFromCsv {
param(
[Parameter(Mandatory)]
[string] $Path,
[ValidatePattern("\w[\w\d_-]*", ErrorMessage = "The typename must be a valid name of an Identifier.")]
[string] $NameOfGeneratedType,
[ArgumentCompletions('";"', '"`t"', '","')]
[string] $Delimiter = ',',
[Type[]] $ColumnType,
[switch] $CSharp
)
$PSBoundParameters.Remove("NameOfGeneratedType") | Out-Null
$PSBoundParameters.Remove("ColumnType") | Out-Null
$PSBoundParameters.Remove("CSharp") | Out-Null
$firstObject = Import-Csv @PSBoundParameters | Select-Object -first 1
[string[]] $props = $firstObject.psobject.Properties.name
$def = if ($CSharp) {
@"
namespace CSVImport {
public class $NameOfGeneratedType {
$(
for($i = 0; $i -lt $props.Length; ++$i){
$prop = $props[$i]
$colType = if ($null -eq $columnType) {[object]} else {$ColumnType[$i]}
if ($null -eq $colType) {
$colType = object;
}
"`tpublic $colType $prop {get;set;}`r`n"
}
)
}
}
"@
}
else {
@"
class $NameOfGeneratedType {
$(
for($i = 0; $i -lt $props.Length; ++$i){
$prop = $props[$i]
$colType = if ($null -eq $columnType) {[object]} else {$ColumnType[$i]}
if ($null -eq $colType) {
$colType = [object];
}
"`t[$colType] `$$prop`r`n"
}
)
}
"@
}
Write-Debug $def
$def
}
function Import-CsvWithType {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $Path,
[Parameter(Mandatory)]
[ValidatePattern("\w[\w\d_-]+", ErrorMessage = "The typename must be a valid name of an Identifier.")]
[string] $NameOfGeneratedType,
[ArgumentCompletions('";"', '"`t"', '","')]
[string] $Delimiter = ',',
[Type[]] $ColumnType
)
$def = New-TypeDefinitionFromCsv @PSBoundParameters
Invoke-Expression $def | out-null
$type = Invoke-Expression "[$NameOfGeneratedType]"
$PSBoundParameters.Remove("NameOfGeneratedType") | Out-Null
$PSBoundParameters.Remove("ColumnType") | Out-Null
foreach($obj in Import-Csv @PSBoundParameters){
[System.Management.Automation.LanguagePrimitives]::ConvertTo($obj, $type)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment