Quick way to convert CSV types to original types with PowerShell's Import-Csv cmdlet?

故事扮演 提交于 2020-01-02 08:57:28

问题


I'm using PowerShell v2 and have a custom type I've defined called Material using code like this:

add-type @"
public struct Material {
    public string BusinessUnit;
    public string Source;
    public string PrimarySource;
    public string LegacyMaterialNumber;
}
"@

...and I've got a collection of objects of this type I'm writing to a CSV file using the Export-Csv cmdlet. That works fine and produces data with the original type specified like this:

#TYPE Material          
BusinessUnit,Source,PrimarySource,LegacyMaterialNumber
BU1,NAFO,NAFO-FG,17502
BU1,NAFO,NAFO-FG,17504
BU1,NAFO,NAFO-FG,17739
BU1,NAFO,NAFO-FG,17837
BU1,NAFO,NAFO-FG,17841

The issue I'm running into is when I import this data back using Import-Csv each line is created as the type:

CSV:Material

...instead of the original type I started with:

Material

In my specific case this is an issue because I want to pass each Material into a function with a parameter specifically typed as Material. I could parse each row and rebuild my Material objects with the data of course, but is there a quick way to just import the CSV data as the original type?


回答1:


Import-Csv wants to create a PSObject based type. You can create a conversion function (or filter) to convert to a Material type. Then pipe the output of import-csv to this function and into your target array:

filter convert-csvToMaterial([Parameter(Mandatory=$true,ValueFromPipeline=$true)]$csvMaterial)
{
    $material = new-object -TypeName Material 
    $material.BusinessUnit = $csvMaterial.BusinessUnit
    $material.LegacyMaterialNumber = $csvMaterial.LegacyMaterialNumber
    $material.PrimarySource = $csvMaterial.PrimarySource
    $material.Source = $csvMaterial.Source
    $material
}

$importedMaterial = import-csv .\materialList.csv | convert-csvToMaterial



回答2:


Another option would be to dynamically create a hashtable from the custom objects returned by Import-Csv and use them as the -Property argument to New-Object:

filter Convert-CsvToType( [string]$TypeName ) {
  $_.PSObject.Properties |
    foreach { $h = @{} } {
      $h[$_.Name] = $_.Value
    } { New-Object $TypeName -Property $h }
}

Import-Csv .\materialList.csv | Convert-CsvToType Material


来源:https://stackoverflow.com/questions/17857385/quick-way-to-convert-csv-types-to-original-types-with-powershells-import-csv-cm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!