Variable not passed properly

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 1 month ago.

  • Author
    Posts
  • #19629
    Profile photo of Jason McMahan
    Jason McMahan
    Participant

    I am attempting to pass the property of users account for thier supervisor then, perform an ad lookup on that id to return the supervisors ad account but it is failing.

    $externalUser = get-aduser -identity jack1 -properties SamAccountName, Mail,supervisorID

    Once i have the variable externalUser populated i then perform a lookup using the supervisorID such as this

    get-aduser -filter {ldapID -like "$externalUser.supervisorID"} -properties name

    When i press enter nothing is returned and no error appears (either in ise or powershell console)

    if i fill $a = get-aduser -filter {ldapID -like "$externalUser.supervisorID"} -properties name
    then perofrm $a.gettype() it returns You cannot call a method on a null-valued expression

    I bet i am missing something easy but would love a nudge in the right direction please.

    Thank you

  • #19630
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That's a common gotcha when working with the AD cmdlets' -Filter parameter. It actually takes a string rather than a ScriptBlock, and while all ScriptBlocks can be casted to strings, the results are sometimes not what you expect (particularly when trying to access the properties of variables, such as $externalUser.SupervisorID).

    I've found that it helps to do one of two things:

    # Either assign the value you want to compare directly to a variable, instead of needing a member expression:
    
    $supervisorID = $externalUser.SupervisorID
    Get-ADUser -Filter { ldapID -like $supervisorID } -Properties Name
    
    # Or, just build a string and have complete control over how variable expansion is done:
    
    Get-ADUser -Filter "ldapID -like '$($externalUser.supervisorID)'" -Properties Name
    
    # (Note the single quotes around $($externalUser.supervisorID) )
    
    
  • #19631
    Profile photo of Jason McMahan
    Jason McMahan
    Participant

    Thank you soooo very much i knew i was close but was just barely off instead of

    Get-ADUser -Filter "ldapID -like '$($externalUser.supervisorID)'"
    

    I tried

    Get-ADUser -Filter {LdapId -eq '$($externalUserID.SupervisorID)'}
    

    But of course it failed. Thank you for showing me the error, and fast response, i appreciate the correction.
    Have a wonderful weekend.

  • #19632
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    No problem, happy to help! 🙂

You must be logged in to reply to this topic.