gpt4 book ai didi

powershell - 为什么此函数不适用于管道变量?

转载 作者:行者123 更新时间:2023-12-04 17:21:05 26 4
gpt4 key购买 nike

我创建了这个函数来解析特定文本的字段并返回一个自定义对象。

如果我使用语法 Get-MachineUser -VMArray $PassedArray 一切正常,但如果我通过管道传递数组 $PassedArray | 则一切正常。获取机器用户

我与团队中的某个人一起工作,我们发现当我们传递数组时,它只处理数组中的最后一个条目。我不介意使用其他语法,但我很好奇我有什么错误导致管道无法工作。

function Get-MachinesUser{
param (
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[System.Object[]] $VMArray
)
foreach($vm in $VMArray){
if($VM.Description -match '.*(ut[A-Za-z0-9]{5}).*'){
[PSCustomObject]@{
"Name" = $vm.Name
"User" = $Matches[1]
}
}
}
}

最佳答案

要支持管道输入,您需要在函数中添加一个进程 block :

function Get-MachinesUser{
param (
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[System.Object[]] $VMArray
)
Process{
foreach($vm in $VMArray){
if($VM.Description -match '.*(ut[A-Za-z0-9]{5}).*'){
[PSCustomObject]@{
"Name" = $vm.Name
"User" = $Matches[1]
}
}
}
}
}

Process

This block is used to provide record-by-record processing for the function. This block might be used any number of times, depending on the input to the function. For example, if the function is the first command in the pipeline, the Process block will be used one time. If the function is not the first command in the pipeline, the Process block is used one time for every input that the function receives from the pipeline.

Source: https://ss64.com/ps/syntax-function-input.html

(Note: The quote has been slightly amended as SS64 incorrectly indicated that the process block is not executed where there is no pipeline input, whereas in fact it still executes a single time).

包含 ForEach 循环仍然是正确的,因为这意味着您在通过参数传递数组输入时支持它。然而,为了在通过管道发送时处理所有输入,需要一个 Process { } block 。

关于powershell - 为什么此函数不适用于管道变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43925789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com