DirectoryServices - Query for DN

Jan Nitka (DHL IT Services) 26 Reputation points
2020-11-10T13:55:50.773+00:00

Hello,

Need help with bellow, as for some machines I got no results and for some it returns LDAP DN.

Is there any pre-requisite in order for this to work, or what I should check?

$ComputerName=$env:ComputerName

Function Get-ComputerDN($ComputerName){
$root = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectClass=computer) (CN=$ComputerName))"
$adfind = $searcher.findall()
$DN = $adfind
Return $DN.path
}

Write-Host $env:ComputerName
Write-Host $ComputerName
Write-Host $computerDN

38851-asdasdasaa.png

Regards,
Jan

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. SChalakov 10,576 Reputation points MVP Volunteer Moderator
    2020-11-10T14:56:20.47+00:00

    Hi Jan,

    you need to call the function, like in the example below:

    38854-image.png

    Please note that the format is not exactly a DN (It begins with LDAP*).
    There is a lot simpler way to get the DN of a computer in AD. Please check the example below:

    38795-image.png

    Here is also the code:

    $ComputerName=$env:ComputerName  
    $ComputerDN = (Get-ADComputer -Identity $ComputerName -Properties *).DistinguishedName  
    Write-Host $ComputerDNS  
    

    I hope I was able to help you out!

    ----------

    (If the reply was helpful please don't forget to upvote or accept as answer, thank you)
    Regards,
    Stoyan

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jan Nitka (DHL IT Services) 26 Reputation points
    2020-11-10T16:13:26.183+00:00

    Oh my bad, I was looking for difference, as on test device it was reporting result, but it was probably something cached.

    Thanks


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.