使用 PowerShell 的 Import-Csv cmdlet 将 CSV 类型转换为原始类型的快速方法? [英] Quick way to convert CSV types to original types with PowerShell's Import-Csv cmdlet?
问题描述
我正在使用 PowerShell v2 并使用如下代码定义了一个名为 Material 的自定义类型:
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;
}
"@
...而且我有一组这种类型的对象,我正在使用 Export-Csv cmdlet 写入 CSV 文件.这工作正常并生成具有如下指定原始类型的数据:
...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
我遇到的问题是当我使用 Import-Csv 将这些数据导入回时,每一行都被创建为类型:
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
在我的特定情况下,这是一个问题,因为我想将每个 Material 传递给一个函数,该函数具有一个专门键入为 Material 的参数.我当然可以解析每一行并使用数据重建我的 Material 对象,但是有没有一种快速的方法可以将 CSV 数据作为原始类型导入?
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?
推荐答案
Import-Csv
想要创建一个基于 PSObject
的类型.您可以创建转换函数(或过滤器)以转换为材料类型.然后将 import-csv
的输出通过管道传送到此函数并输入您的目标数组:
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
这篇关于使用 PowerShell 的 Import-Csv cmdlet 将 CSV 类型转换为原始类型的快速方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!