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:
- While seductively convenient, avoid the use of script blocks (
{ ... }) as-Filterarguments with AD (Active Directory) cmdlets, because it is conceptually problematic and can lead to misconceptions.
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-Filterargument, 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).