Link to home
Start Free TrialLog in
Avatar of PwrShell
PwrShell

asked on

Running query on AD

I'm trying to run this function/script on PSH; but I get the following error message.

Unexpected token '}' in expression or statement.
At C:\scripts\Dynamic_DN.ps1:34 char:2
+} <<<<
      + CategoryInfo            :  ParserError: (}:String) [ ], ParseException
      + FullyQualifiedErrorId      : UnexpectedToken

---
I function generates the DN dynamically
See script below:


function GetUserDN([string]$username)
{

$objADSI = [adsi]""
$domain = $objADSI.distinguishedname
$objDomain = [adsi]("LDAP://" + $domain)

$search = New-Object System.DirectoryServices.DirectorySearcher
$search.SearchRoot = $objDomain
$search.Filter = "(sAMAccountName=$username)"
$search.SearchScope = "Subtree"

$result = $search.FindOne()
if($result -eq $null)
{
return $null
} else {
return $result.GetDirectoryEntry().distinguishedName
     }
}

$username="administrator"
$userDN=GetUserDN($username)
if($userDN -eq $null)
{
Write-Host ("Unable to find " + $username)
} else {
Write-Host ($username + " - " + $userDN)
     }
}
Avatar of Brent Challis
Brent Challis
Flag of Australia image

Rather than using the ADSI work directory, can you use the Microsoft ActiveDirectory Module and associated cmdlets?  These require a 2008 R2 DC or the gateway services installed on to a pre 2008 R2 DC.  Then you can use cmdlets such as Get-ADUser.
SOLUTION
Avatar of Neil Russell
Neil Russell
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes well spotted! I said the wrong one, its the very very last one you need to delete!
Avatar of PwrShell
PwrShell

ASKER

Thank you. I'm just learning PSH so even though the code made sense after reading the book I guess I'm still adding or missing extra brackets. This Removing the bracket solved the problem.
Also, I will download and start using the Quest Tools. Never heard of them; but if these tools can compress the entire code to that one line, that is great. Thank you again.
Thank you for following up on this. I wanted to give points to 3 different users who helped with the question. One of them answered the question; but missed the wrong } symbol, so i awarded the correct answer to the person who got the } correct. But I would give points to both. Also the person who suggested using the Quest clmlets deserves points for suggesting tools that are great time savers and efficient at solving future queries/problems that may arise when working with PSH.