Home > Software design >  Struggling with PSCustomObject in Compare-Object
Struggling with PSCustomObject in Compare-Object

Time:10-02

Question:

Anyone understand why I'm receiving the following error for my title property in my PSCustomObject inside a foreach? I understand what the error is stating, just confused on the 'why' of it. Everything else works, I'm confused why $_.inputobject returns "Firstname Lastname" just fine in the user property, but can't be used in -filter scriptblock and is unrecognized as an object type in PSCustomObject even though it returns the expected value in the user column.

Error:

Get-ADUser : Property: 'inputobject' not found in object of type: 'System.Management.Automation.PSCustomObject'.

Code:

Compare-Object -ReferenceObject $users.name -DifferenceObject $results.user | foreach {
    $_.sideindicator = $_.sideindicator -replace "<=","No assigned device"
    [PSCustomObject]@{
        user = $_.inputobject
        title = Get-ADUser -Filter {name -like $_.inputobject} -Properties * | % title
        device_status = $_.sideindicator
    }
} 

CodePudding user response:

First, the standard advice applies:

Second, the solution is to use an expandable (double-quoted) string ("...") instead:

Get-ADUser -Filter "name -eq `"$($_.inputobject)`"" -Properties title

Note: Given that your operand contains no wildcard metacharacters, there's no reason to use -like.

As for the error message:

  • At least historically, only simple, stand-alone variable references - e.g., $_ - were supported in the string that is (ultimately) passed to the [string]-typed -Filter argument, not also expressions, which inlcudes attempts to access a property, e.g. $_.InputObject

  • The error message suggests that the AD provider - now? - does try to evaluate an expression such as $_.InputObject, but - seemingly - only looks for type-native properties, whereas a [pscustomobject] instance's properties are dynamic properties.

  • Perhaps someone can shed more light on this (I don't have access to AD).

  • Related