无法将值传递给函数

问题描述

我试图提出一个条件,如果列中的值等于我将要创建的新列,则发布来自我的其他值的值。但是我的函数无法从我的数据中获取值。有什么建议吗?

function MainGroupChoice{        
    param (
        [Parameter(ValuefromPipeline = $true)][String] $value1,[Parameter(ValuefromPipeline = $true)][String] $value2,[Parameter(ValuefromPipeline = $true)][String] $choice1,[Parameter(ValuefromPipeline = $true)][String] $choice2
    )    

    if ($value1 -eq $value2) {
        return
        Add-Member -NotePropertyName MainGroup -NotePropertyValue $choice1 -Passthru  -Force
    }
    else {
        return
        Add-Member -NotePropertyName MainGroup -NotePropertyValue $choice2 -Passthru  -Force
    }
}



$table2 = $nestedGroupUsers | MainGroupChoice -choice1 $ADgroupname.name -choice2 $groupnestedname -value1 $table2.ParentGroup -value2 $nestedmember.distinguishedname

我遇到了这个错误

The input object cannot
     | be bound to any
     | parameters for the
     | command either because
     | the command does not
     | take pipeline input or
     | the input and its
     | properties do not match
     | any of the parameters
     | that take pipeline
     | input.

解决方法

我已经在下面回答了您的问题,但我觉得有义务告诉您,这个单行代码很可能与下面的所有代码一样:

$nestedGroups |Select Value*,@{Name='MainGroup';Expression={if($_.value1 -eq $_.value2){$_.choice1}else{$_.choice2}}}

看起来你会想要:

  1. 声明一个参数以接收整个输入对象(以便您可以稍后修改和/或返回它),然后
  2. 标记其余参数ValuefromPipelineByPropertyName(而不是ValuefromPipeline),最后
  3. 将代码移动到一个显式的 process {} 块中 - 这将确保它对通过管道绑定的每个输入对象执行一次
function MainGroupChoice {
    param (
        [Parameter(ValueFromPipeline)]$InputObject,[Parameter(ValuefromPipelineByPropertyName = $true)][String] $Value1,[Parameter(ValuefromPipelineByPropertyName = $true)][String] $Value2,[Parameter(ValuefromPipelineByPropertyName = $true)][String] $Choice1,[Parameter(ValuefromPipelineByPropertyName = $true)][String] $Choice2
    )    

    process {
        if ($value1 -eq $value2) {
            return $InputObject |Add-Member -NotePropertyName MainGroup -NotePropertyValue $choice1 -PassThru  -Force
        }
        else {
            return $InputObject |Add-Member -NotePropertyName MainGroup -NotePropertyValue $choice2 -PassThru  -Force
        }
    }

}

使用一些模拟输入进行测试:

@(
  [pscustomobject]@{
    Value1 = 123
    Value2 = 123
    Choice1 = "Pick me!"
    Choice2 = "Not me..."
  }
  [pscustomobject]@{
    Value1 = 123
    Value2 = 456
    Choice1 = "Not me..."
    Choice2 = "Pick me!"
  }
) |MainGroupChoice |Select Value*,MainGroup

...我们应该期待输出如下:

Value1 Value2 MainGroup
------ ------ ---------
   123    123 Pick me!
   123    456 Pick me!