Skip to content

PipelineVariable throws error if variable name used exists in function definition #16155

@chadbaldwin

Description

@chadbaldwin

Prerequisites

Steps to reproduce

Sample function:

function Invoke-AddOne {
    param (
        [Parameter(ValueFromPipeline)]
        [string[]]$Number
    )

    Process {
        $testValue = $_ + 1
        $testValue
    }
}

Run each command to recreate error:

1,2,3 | Invoke-AddOne -PV test # does not throw error
1,2,3 | Invoke-AddOne -PV testValue # does throw error

If this is a matter of me writing an improper example, please let me know. I see the error mentions the use of Remove-Variable, but I've never heard of any recommendations to use Remove-Variable for custom written functions. If this the case and I just need to add Remove-Variable to my functions, then my apologies.

Expected behavior

When the function is called while supplying a -PipelineVariable value, it should work as normal, storing the pipeline value within the variable name to be used downstream in the pipeline.

PS> 1,2,3 | Invoke-AddOne -PV test | % { $test }
2
3
4

Does not return any errors

Actual behavior

When a variable name that is used in the definition of the function is supplied as a -PipelineVariable variable name, it throws an error.

PS> 1,2,3 | Invoke-AddOne -PV testValue | % { $testValue }
Invoke-AddOne: Cannot remove variable testValue because the variable has been optimized and is not removable. Try using the Remove-Variable cmdlet (without any aliases), or dot-sourcing the command that you are using to remove the variable.

Error details

PS> Get-Error

Exception             :
    Type        : System.Management.Automation.SessionStateUnauthorizedAccessException
    ErrorRecord :
        Exception             :
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : Cannot remove variable testValue because the variable has been optimized and is not removable. Try using the Remove-Variable cmdlet (without any aliases), or dot-sourcing the command that you are using to remove the variable.
            HResult : -2146233087
        TargetObject          : testValue
        CategoryInfo          : WriteError: (testValue:String) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : VariableNotRemovableRare
    ItemName    : testValue
    TargetSite  :
        Name          : RemoveVariable
        DeclaringType : System.Management.Automation.SessionStateScope, System.Management.Automation, Version=7.2.0.9, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message     : Cannot remove variable testValue because the variable has been optimized and is not removable. Try using the Remove-Variable cmdlet (without any aliases), or dot-sourcing the command that you are using to remove the variable.
    Source      : System.Management.Automation
    HResult     : -2146233087
    StackTrace  :
   at System.Management.Automation.SessionStateScope.RemoveVariable(String name, Boolean force) in System.Management.Automation.dll:token 0x6003bdf+0x46
   at System.Management.Automation.SessionStateInternal.RemoveVariable(String name, Boolean force) in System.Management.Automation.dll:token 0x6003b9d+0x2a
   at System.Management.Automation.PSScriptCmdlet.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess) in System.Management.Automation.dll:token 0x600368b+0x125
   at System.Management.Automation.PSScriptCmdlet.DoProcessRecord() in System.Management.Automation.dll:token 0x6003687+0x3b
   at System.Management.Automation.CommandProcessor.ProcessRecord() in System.Management.Automation.dll:token 0x6002100+0x1ae
TargetObject          : testValue
CategoryInfo          : WriteError: (testValue:String) [Invoke-AddOne], SessionStateUnauthorizedAccessException
FullyQualifiedErrorId : VariableNotRemovableRare,Invoke-AddOne
InvocationInfo        :
    MyCommand        : Invoke-AddOne
    ScriptLineNumber : 1
    OffsetInLine     : 9
    HistoryId        : 10
    Line             : 1,2,3 | Invoke-AddOne -PV testValue | % { $testValue }
    PositionMessage  : At line:1 char:9
                       + 1,2,3 | Invoke-AddOne -PV testValue | % { $testValue }
                       +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    InvocationName   : Invoke-AddOne
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1

Environment data

PS> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.2.0-preview.9
PSEdition                      Core
GitCommitId                    7.2.0-preview.9
OS                             Microsoft Windows 10.0.22000
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugIssue has been identified as a bug in the productResolution-FixedThe issue is fixed.WG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions