Strict-Mode | Where-Object

Welcome Forums General PowerShell Q&A Strict-Mode | Where-Object

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
1 week, 4 days ago.

  • Author
    Posts
  • #113503

    Participant
    Points: 0
    Rank: Member

    Using StrictMode, how can we filter the objects in the pipeline, when some of them don't have the property set? When the Object doesn't have the property set we get the error "The input name "xxxx" cannot be resolved to a property"

    If we force the property on the Select-Object statement, the property is always present. But if we need to select all the properties and force the property we want to fiter on, we get an error saying "the property "xxxx" already exists".

    I can bypass this using the ErrorAction Ignore on the Select-Object command. Is this the only way to do it?

    Set-StrictMode -Version Latest
    
    # Two AD Accounts UserWithMailbox, UserWithoutMailbox
    $x = Get-ADUser -filter 'samaccountname -like "User*"' -Properties *
    
    $x | Where-Object HomeMDB -ne $null | Select-Object SamAccountName, HomeMDB
    # Where-Object : The input name "HomeMDB" cannot be resolved to a property.
    
    $x | Select -Property HomeMDB, * | Select-Object SamAccountName, HomeMDB
    # Select : The property cannot be processed because the property "homeMDB" already exists
    
    $x | Select HomeMDB, HomeMDB -ErrorAction Ignore | Select-Object SamAccountName, HomeMdb
    
    # Create new Object with the property HomeMDB Allways Set
    $y = $x | Select HomeMDB, * -ErrorAction Ignore
    $y.HomeMDB.count
    
  • #113533

    Participant
    Points: 10
    Rank: Member

    Remember that the goal of Set-StrictMode, is for dev work and to keep you from using uninitialized stuff.

    So, it is working as designed. It really should not be used / commented out in production use case.

    As for bypass, yep, that's what you got.

    Again, it's a self-imposed code sanity wall only. You never have to use it, but you should, at least in dev / debug use case. Once you get to user acceptance and prod, well, you know.

You must be logged in to reply to this topic.