【问题标题】:Does Select-Object modify the input?Select-Object 是否修改输入?
【发布时间】:2012-05-04 03:23:19
【问题描述】:

this question 之后,似乎 Select-Object 将其输入设置为 null 作为其处理的一部分。这对我来说似乎是错误的。这是我正在尝试做的事情:

$sessionInput = new-object -TypeName System.Object
$sessionInput | Add-Member -MemberType NoteProperty -Name Foo -Value $foo
$sessionInput | Add-Member -MemberType NoteProperty -Name Bar -Value $bar
Invoke-Command -Session $session -InputObject $sessionInput {
    $foo = $input | Select-Object -ExpandProperty Foo
    $bar = $input | Select-Object -ExpandProperty Bar

    # Expected: $foo, $bar inside the session = $foo, $bar outside the session
}

实际发生的是只有$foo 有它的期望值,而$bar 总是$null。经过一番调查,事实证明$input 在第一次运行Select-Object 后被设置为$null。例如,在两个 Select-Object 行之间插入 $input | Get-Member 会引发错误,指出“没有为 get-member cmdlet 指定对象。”

这是怎么回事?

【问题讨论】:

    标签: powershell powershell-2.0 powershell-remoting


    【解决方案1】:

    此实例中 $input 的类型是[System.Management.Automation.Runspaces.PipelineReader`1+GetReadEnumerator>d__0[[System.Object]]]。执行$inputParameters = $input | Select-Object 以从管道中读取对象并将其隐藏起来具有预期的效果:$inputParameters 的类型为PSCustomObject,并且可以通过调用Select-Object 进一步多次戳。

    【讨论】:

    • 另外,Select-Object 创建新对象,并复制您要求的属性值。
    【解决方案2】:

    这行得通吗?指定 $SomeVar = $Input 然后调用它?

    $sessionInput = new-object -TypeName System.Object
    $sessionInput | Add-Member -MemberType NoteProperty -Name Foo -Value $foo
    $sessionInput | Add-Member -MemberType NoteProperty -Name Bar -Value $bar
    Invoke-Command -Session $session -InputObject $sessionInput {
        $TempInput = $input
        $foo = $TempInput | Select-Object -ExpandProperty Foo
        $bar = $TempInput | Select-Object -ExpandProperty Bar
    
        # Expected: $foo, $bar inside the session = $foo, $bar outside the session
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2011-08-22
      • 2014-04-01
      • 2017-12-16
      相关资源
      最近更新 更多