【问题标题】:PowerShell, How to provide a pipe variable?PowerShell,如何提供管道变量?
【发布时间】:2019-03-09 14:09:32
【问题描述】:

这是一个高级别的问题,因为我不在办公室,而是在家里,所以细节可能并不准确。

我有一个通过管道接受变量的函数:

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,它直接通过$_ 访问管道变量?

【问题讨论】:

  • @mklement0,我唯一的意图是将读取 .csv 替换为从变量提供,所有其余部分都陷入黑暗。对于Color = ‘Red’; Doors = 4; Convertible = $false 的示例.csv 输入,请忽略并告诉我正确的做法。谢谢。
  • 您可以将哈希表用于splatting 函数的参数,而不是管道。附:摆脱卷曲的“智能引号”并使用直引号。
  • 感谢@Theo 的链接。它可能不适合我的具体情况,因为我的myfunc() 直接通过$_. 访问管道变量,而不是定义Params。

标签: powershell object pipe pscustomobject


【解决方案1】:

Import-Csv(不是Get-Csv),用于从文件读取CSV数据,ConvertFrom-Csv,用于读取CSV来自字符串的数据,输出一个自定义对象的集合(类型[pscustomobject],其属性反映了CSV数据的列。

要按需构造此类自定义对象以模拟 Import-Csv / ConvertFrom-Csv 输入,请使用
[pscustomobject] @{ <propertyName>=<value>; ... } 语法 (PSv3+)。

例如,模拟 2 行包含 ColorDoors 列的 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 中,echoWrite-Output 的别名,很少需要显式使用;相反,该函数依赖于 PowerShell 的隐式输出:字符串连接 (+) 的结果隐式成为函数的输出。

以上产量:

Color: Red
Color: Blue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2023-01-27
    • 2021-12-05
    相关资源
    最近更新 更多