Import-Csv(不是Get-Csv),用于从文件中读取 CSV 数据,以及ConvertFrom-Csv,用于从字符串中读取 CSV 数据,输出一组自定义对象(类型[pscustomobject]),其属性反映 CSV 数据的列。
要按需构造此类自定义对象以模拟 Import-Csv/ConvertFrom-Csv输入,请使用
[pscustomobject] @{ <propertyName>=<value>; ... }语法 (PSv3+)。
Color例如,模拟 2 行包含、Doors和列的 CSV 数据Convertible:
[pscustomobject] @{ Color = 'Red'; Doors = 4; Convertible = $false },
[pscustomobject] @{ Color = 'Blue'; Doors = 5; Convertible = $false } |
...
另外,为了通过自动变量从管道对象逐个对象$_进行函数处理输入,它必须有一个process { ...}块- 请参阅帮助主题about_Functions。
# Define the function body with a process { ... } block, which
# PowerShell automatically calls for each input object from the pipeline,
# reflected in automatic variable $_
function showThem { process { "Color: " + $_.Color } }
[pscustomobject] @{ Color = 'Red'; Doors = 4; Convertible = $false },
[pscustomobject] @{ Color = 'Blue'; Doors = 5; Convertible = $false } |
showThem
注意:在 PowerShell 中,echo是 的别名Write-Output,很少需要显式使用;相反,该函数依赖于 PowerShell 的隐式输出:字符串连接 ( +) 的结果隐式地成为函数的输出。
以上产生:
Color: Red
Color: Blue