Search code examples
powershellvariablesget-aduser

Why are variables not working with Get-Aduser in powershell?


Looking for a little explanation as to why this isn't working and what I might be doing wrong. Any Help would be great!

Expected Results : BSMITH

Get-Aduser -filter {(givenname -eq "Bob") -and (surname -eq "Smith"))} | select-object SamAccountName

Result : BSMITH

Works Fine. Good to go


Expected Result : BSMITH

$textbox_FirstName = "Bob"
$textbox_LastName = "Smith"

Get-Aduser -filter {(givenname -eq "$textbox_FirstName.text") -and (surname -eq "$textbox_LastName.text")} | select-object SamAccountName

Result : (Blank Nothing)

I have tried givenname -eq "$textbox_FirstName.text" without quotes, without .text, with no quotes at all. Still no results :(


Solution

  • Both variables are of the type string they don't have a .text property, in addition adding double quotes to your variable would expand the variable and concatenate .text:

    $textbox_FirstName = "Bob"
    "$textbox_FirstName.Text" => Bob.Text
    

    Any of these options should give you the output you expect:

    Get-Aduser -Filter {GivenName -eq $textbox_FirstName -and Surname -eq $textbox_LastName}
    
    Get-Aduser -Filter "GivenName -eq '$textbox_FirstName' -and Surname -eq '$textbox_LastName'"
    
    Get-Aduser -LDAPFilter "(&(GivenName=$textbox_FirstName)(Surname=$textbox_LastName))"