Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current computer's distinguished name in powershell without using the ActiveDirectory module

I have a script that I need to find the full Distinguished name (CN=MyComputer, OU=Computers, DC=vw, DC=local) of the computer it is running on, however I can not guarantee that the ActiveDirectory module will be available on all computers that this script will be run on. Is there a way to get the current computer's full Distinguished name without using Get-ADComputer $Env:COMPUTERNAME?


Just in case this is a XY problem, what I am trying to do is move the computer to a specific OU, but I need a way to get the ASDI entry for the computer I am running on.

[ADSI]$computer = ("LDAP://" + $localDN)
if($Production)
{
    [ADSI]$destination = 'LDAP://ou=Production,ou=Computers,ou=VetWeb,dc=vw,dc=local'
    $computer.MoveTo($destination);
}
else
{
    [ADSI]$destination = 'LDAP://ou=Test,ou=Computers,ou=VetWeb,dc=vw,dc=local'
    $computer.MoveTo($destination);
}
like image 526
Scott Chamberlain Avatar asked Jun 21 '12 20:06

Scott Chamberlain


2 Answers

Try this (requires v2):

$filter = "(&(objectCategory=computer)(objectClass=computer)(cn=$env:COMPUTERNAME))"
([adsisearcher]$filter).FindOne().Properties.distinguishedname
like image 166
Shay Levy Avatar answered Nov 04 '22 00:11

Shay Levy


Be careful with the ADSIsearcher method. If you have two computers with the same name in different domains in the same forest (the issue that caused me to perform the search that returned this article), this method is not guaranteed to return the correct one. This method will simply search in AD for a computer with the name returned by the ComputerName Environment Variable. You need to be sure to cross-reference the domain to which the computer is joined if you are in an environment with multiple domains in a forest.

Moderator, this should really be a comment to the answer by Shay Levy, but I cannot make a comment because I am new.

like image 44
joesuffceren Avatar answered Nov 03 '22 22:11

joesuffceren