Skip to content

Null Conditional Member Access Invokes Argument Multiple Times #24716

Description

@pinkfloydx33

Prerequisites

Steps to reproduce

Write an expression of the form (<command>)?.a?.b and note that <command> is executed/recomputed multiple times, depending on the number of conditional accesses, whether they were successful (non-null) or if nested objects are involved. I've not be able to figure out the exact pattern/rules behind it.

I noticed this originally when debugging a script that for some reason was calling my API multiple times (creating multiple objects). It turned out to be because I was doing something to similar to (Invoke-RestMethod ...)?.something?.else.

I'm also not sure if this is technically a bug or not. I would assume that it is especially when you compare the behavior to the direct/non-conditional access behavior. I did search the issues, however it is quite difficult given the syntax involved, so apologies if I've missed something.

Expected behavior

All of the below should behave like the non conditional access and only invoke the expressions once

> $(Write-Host "blah"; @{ x=1 })?.x  
blah
1

# one time, not eight!
> $(Write-Host "blah"; @{ x=@{ z=2 } }).x.z.y
blah

Actual behavior

Expression is invoked multiple times, depending on the order of conditional access and level of nested objects

> $(Write-Host "blah"; @{ x=1 })?.x  
blah
blah 
1

> $(Write-Host "blah"; @{ x=1 })?.x?.y
blah
blah
blah
blah

# remove the last conditional and reduce to two times
> $(Write-Host "blah"; @{ x=1 })?.x.y
blah
blah

# now invert it and start with a known absent prop
> $(Write-Host "blah"; @{ x=1 })?.y
blah
blah

# stays the same for further accesses
> $(Write-Host "blah"; @{ x=1 })?.y?.x
blah
blah

# but now nest some objects.... eight times!
> $(Write-Host "blah"; @{ x=@{ z=2 } })?.x?.z?.y
blah
blah
blah
blah
blah
blah
blah
blah

Error details

N/A

Environment data

Name                           Value
----                           -----
PSVersion                      7.4.6
PSEdition                      Core
GitCommitId                    7.4.6
OS                             Microsoft Windows 10.0.26100
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

Labels

In-PRIndicates that a PR is out for the issueNeeds-TriageThe issue is new and needs to be triaged by a work group.

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions