powershellactive-directoryfilteringget-aduser

Struggling with PSCustomObject in Compare-Object


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
    }
} 

Solution

  • 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: