这是一个高级别的问题,因为细节可能不准确,因为我不在办公室,而是在家里。
我有一个通过管道接受变量的函数:
get-csv | myfunc
管道源是.csv文件中的字段。
如何定义变量并传递到myfunc()
中? HashTable
会好吗?
$my_pipe_variables = @{ Color = ‘Red’; Doors = 4; Convertible = $false}
$my_pipe_variables | myfunc
这是正确的语法吗?
更新:
我终于可以尝试一下,但是它对我不起作用,因为我的myfunc
直接通过$_
访问管道变量。这是演示:
function showThem { echo Color: $_.Color }
> [pscustomobject]@{ Color = ‘Red’; Doors = 4; Convertible = $false} | showThem
Color:
如何使它适用于myfunc
,后者可以直接通过$_
访问管道变量?
答案 0 :(得分:3)
Import-Csv
(不是Get-Csv
),用于从文件和 ConvertFrom-Csv
中读取CSV数据strong>,要从字符串中读取CSV数据,输出一个自定义对象(类型[pscustomobject]
)的集合,其属性反映了CSV数据的列。
要按需构造此类自定义对象以 模拟 Import-Csv
/ ConvertFrom-Csv
输入,请使用
{{1 }}语法(PSv3 +)。
例如,使用列[pscustomobject] @{ <propertyName>=<value>; ... }
,Color
模拟2行CSV数据,
和Doors
:
Convertible
另外,为了通过自动变量[pscustomobject] @{ Color = 'Red'; Doors = 4; Convertible = $false },
[pscustomobject] @{ Color = 'Blue'; Doors = 5; Convertible = $false } |
...
从管道逐个对象进行功能处理输入,它必须具有一个$_
块-请参见帮助主题about_Functions。
process { ...}
注意:在PowerShell中,# 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
是echo
的别名,很少需要使用它的显式用法。相反,该函数依赖于PowerShell的隐式输出:字符串串联(Write-Output
)的结果隐式成为函数的输出。
以上结果:
+