Skip to content

Set-StrictMode 2: False positive for references to the Count property #16427

Closed

Description

@iRon7

Prerequisites

Steps to reproduce

Set-StrictMode -Version Latest
$TempFile = New-TemporaryFile
$TempPath = Join-Path $Env:Temp ('Folder_' + [Guid]::NewGuid())
$TempFolder = New-Item -ItemType Directory -Path $TempPath
Copy-Item -Path $TempFile -Destination $TempFolder
$TempFolder |Should -Exist
(Get-ChildItem $TempFolder).Count |Should -Be 1

Expected behavior

No Error

Actual behavior

PropertyNotFoundException: The property 'Count' cannot be found on this object. Verify that the property exists.

Error details

With Set-StrictMode -Off the (Get-ChildItem $TempFolder).Count return 1 which shows that the property does exist

Environment data

Name                           Value
----                           -----
PSVersion                      7.2.0
PSEdition                      Core
GitCommitId                    7.2.0
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

Activity

  1. added
    Needs-Triage
    on Nov 10, 2021
  2. added
    Issue-Question
    WG-Security
    on Nov 10, 2021
  3. removed
    Needs-Triage
    on Nov 15, 2021
  4. PaulHigin commented on Nov 15, 2021

    @PaulHigin
    Contributor

    @WG-Security

    iRon7 This is by design. Strict mode emits errors when you reference a property that does not exist. As a workaround you can coerce the result into an array type:

    @(Get-ChildItem $TempFolder).Count 
  5. iRon7 commented on Nov 16, 2021

    @iRon7
    Author

    Paul Higinbotham (@PaulHigin),

    Thanks for the answer.

    As a workaround you can coerce the result into an array type:

    What is the catch?

    What is the difference behind the scene?
    Apparently there is no direct relation with member enumeration as this doesn't give an error:

    ([PSCustomObject]@{ Count = 3 }).Count

    So I guess it has something to do with an deferred execution.
    I used to state that assigning a pipeline or using parenthesis will break it, now I have second thoughts whether this is always the case for using parenthesis. I suspect now that:

    (Get-ChildItem $TempFolder) |ForEach-Object { ... }

    is smart and actually still emitting each item one by one despite the parenthesis.
    And only when it is forced to an array it will choke the pipeline:

    @(Get-ChildItem $TempFolder) |ForEach-Object { ... }

    Or???

  6. PaulHigin commented on Nov 16, 2021

    @PaulHigin
    Contributor

    There is no catch. The above syntax simply wraps the object in an array so that the Count property is valid, when in strict mode. PowerShell has rules about when to unwrap an array type.

    https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.2

    Arrays are a fundamental language feature of most programming languages.
  7. SeeminglyScience commented on Nov 16, 2021

    @SeeminglyScience
    Contributor

    Count is also a binder construct though, similar to the ForEach and Where methods. It's supposed to exist on any object including scalars. I'm not necessarily trying to assert that it shouldn't error, I just want to make sure that's taken into account.

  8. penser-jata commented on Nov 17, 2021

    @penser-jata

    Count not only exists on every object, it is also explicitly (and magically) present on no object at all.
    $null.Count gives 0
    The behavior of .Count, (0 for null, 1 on any scalar object, the number of elements in collections) is intended, extremely useful, and documented.
    StrictMode is not aware of the very special semantics of .Count, so you basically can't use the two of them at the same time.

  9. iRon7 commented on Nov 17, 2021

    @iRon7
    Author

    Thanks for the answers and information.
    It took me a while to see this thru but Get-ChildItem $TempFolder could potentially return nothing (System.Management.Automation.Internal.AutomationNull) and () indeed doesn't have a Count property

    I have closed the issue (Resolution-Answered).

  10. penser-jata commented on Nov 17, 2021

    @penser-jata

    But you can use Count on 'nothing' and it will return zero.
    And for a single object you get one.
    No 'real' property is needed .
    That is the beauty of the feature.

    This wasn't there for the first five years but was added in version 3.
    Experience showed that you often had to use the work around suggested above by Paul Higinbotham (@PaulHigin) where you create an array for single objects. (A little ugly and with non-zero perf cost)

    In that version we also got the equally magic feature where where you can treat any object like an array, so this works and gives 1:

    $a = 1
    $a[0]
    
    

    Interestingly, StrictMode seems to be aware of this 'synthetic indexing operator' and does not complain, but barfs on the the closely related 'synthetic Count property'

    This issue is really a valid bug report and deserves to stay open.

  11. iRon7 commented on Nov 17, 2021

    @iRon7
    Author

    Ok, I am not able to qualify this further. To prevent that I have reopen/close it repeatedly, I will leave it up to you (Patrick Meinecke (@SeeminglyScience), Ilya (@iSazonov) ?) to change it again.

  12. SeeminglyScience commented on Nov 17, 2021

    @SeeminglyScience
    Contributor

    I don't have permissions to reopen (Rain Sallow (/u/ta11ow) (@vexx32)?) but the Count engine intrinsic property works fine on autonull in non-strict (returns 0) so I'm inclined to say it should do the same in strict. If it returned nothing I would say the error makes sense.

  13. reopened this on Nov 17, 2021
  14. vexx32 commented on Nov 17, 2021

    @vexx32
    Collaborator

    That makes sense to me. If strict mode is intended to by design restrict usage of otherwise ubiquitous properties provided by the engine, that should be well documented. Given that it's not (as far as I'm aware?), I would be inclined to assume it's more of an accident of implementation and we should see if it's feasible to rectify the issue.

  15. iRon7 commented on Nov 29, 2021

    @iRon7
    Author

    Something similar happens with the Count property of default array parameters:

    function Test {
        [CmdletBinding()] param(
            [String[]]$StringArray
        )
        $StringArray.Count
    }
    Set-StrictMode -Version Latest
    Test

    The property 'Count' cannot be found on this object. Verify that the property exists.

    The workaround is to default it to an empty array: [String[]]$StringArray = @()


    👎 This isn't the same issue as initial reported, see @mklement0's comment [on 7 Dec 2021]:

    your [string[]] $StringArray parameter example can be reduced to $null.Count, because unbound reference-type parameters (without default values) are $null.

  16. changed the title [-]`Set-StrictMode -Version Latest`: False positive for references to non-existent properties of an object[/-] [+]`Set-StrictMode 2`: False positive for references to the `Count` property[/+] on Nov 29, 2021
  17. PaulHigin commented on Nov 29, 2021

    @PaulHigin
    Contributor

    @WG-Security
    We do not see a security issue here, as strict mode is not a security feature. This is a language issue and we will update the label.

  18. added
    WG-Language
    and removed
    WG-Security
    on Nov 29, 2021
  19. mklement0 commented on Dec 7, 2021

    @mklement0
    Contributor

    Note that this problematic behavior was first reported in

    #15526 also discusses the inconsistency, but argues for the opposite resolution; to borrow from my comment there:

    Engine-supplied members such as .Count, .Length, scalar [...], .psobject, ForEach(), .... now have an official name: intrinsic members.

    It makes much more sense to make them consistently available, irrespective of strict mode.

    This is already true for most of them, but inexplicably not for .Count and .Length ([pscustomobject] being the only exception), despite their tremendous usefulness in unified handling of scalars and collections.

    Simplest repro:

    # .Count fails on all types without their own .Count property  *except* [pscustomobject]`
    # Applies analogously to .Length
    & { Set-StrictMode -Version 2; [pscustomobject] @{ foo=1 }.Count; 'foo'.Count; $null.Count }

    iRon7, your [string[]] $StringArray parameter example can be reduced to $null.Count, because unbound reference-type parameters (without default values) are $null.

  20. added
    Resolution-No Activity
    on Nov 15, 2023
  21. iRon7 commented on Nov 15, 2023

    @iRon7
    Author

    I guess this issue should be marked as Issue-Bug.
    Anyways I have closed this one, assuming that the linked issue #2798 stays open.

  22. removed
    Resolution-No Activity
    on Nov 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-QuestionWG-Language

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions