Author Posts

October 17, 2013 at 6:08 am

I am writing a very simple LDAP query to gather some information on a user based upon a logon ID. The problem is that when I assign a value to $accountid it fails (see below) but when I input the ID for XXXX in (sAMAccountName=XXXX), everything works as expected. In other words, I don't use the variable $accountid but just put in the value directly in the filter statement. What do I need to do to cast the variable $accountid properly so as to be accepted in the filter statement?

$accountid=Read-Host -prompt "Enter the userID for which you want to find info"
$searcher=[ADSISearcher]'(&(objectClass=User)(objectCategory=person)(sAMAccountName=$accountid))'
$hashtbl=$searcher.FindOne()|select -ExpandProperty Properties
$tele=$hashtbl.Get_Item("telephonenumber")
$fullname=$hashtbl.Get_Item("displayname")
$office=$hashtbl.Get_Item("physicaldeliveryofficename")
$email=$hashtbl.Get_Item("mail")
Write-Host "UserID $accountId belongs to $fullname and he/she resides at $office with phone $tele & e-mail $email"

The error rec'd is:
You cannot call a method on a null-valued expression.
At C:\documents and settings\usf48555\My Documents\scripts\UserQry.ps1:4 char:24
+ $tele=$hashtbl.Get_Item <<<< ("telephonenumber") + CategoryInfo : InvalidOperation: (Get_Item:String) [], RuntimeExcept ion + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\documents and settings\usf48555\My Documents\scripts\UserQry.ps1:5 char:28 + $fullname=$hashtbl.Get_Item <<<< ("displayname") + CategoryInfo : InvalidOperation: (Get_Item:String) [], RuntimeExcept ion + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\documents and settings\usf48555\My Documents\scripts\UserQry.ps1:6 char:26 + $office=$hashtbl.Get_Item <<<< ("physicaldeliveryofficename") + CategoryInfo : InvalidOperation: (Get_Item:String) [], RuntimeExcept ion + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\documents and settings\usf48555\My Documents\scripts\UserQry.ps1:7 char:25 + $email=$hashtbl.Get_Item <<<< ("mail") + CategoryInfo : InvalidOperation: (Get_Item:String) [], RuntimeExcept ion + FullyQualifiedErrorId : InvokeMethodOnNull

October 17, 2013 at 6:16 am

Variables are read as literals inside single quotes.

PS> $x = "Hi"
PS> $y = 'This is $x'
PS> $y
This is $x

They are replaced in double quotes.

PS> $x = "Hi"
PS> $y = "This is $x"
PS> $y
This is Hi

October 17, 2013 at 12:00 pm

I have been using powershell since March and this is the first time I noticed that. I'm such a dummy. LOL.

October 17, 2013 at 12:01 pm

Thanks, Don. Having struggled looking at this code too long will hopefully help me to remember this caveat. The script now works.