Get the current distinguished computer 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 on which it is running, however I can not guarantee that the module ActiveDirectorywill be available on all computers, the script will be launched. Is there a way to get the full computer name different from the name without using Get-ADComputer $Env:COMPUTERNAME?


Just in case, this is an XY problem, what I'm trying to do is transfer the computer to a specific unit, but I need a way to get the ASDI record for the computer I'm 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);
}
+6
source share
7 answers

Try this (v2 required):

$filter = "(&(objectCategory=computer)(objectClass=computer)(cn=$env:COMPUTERNAME))"
([adsisearcher]$filter).FindOne().Properties.distinguishedname
+10

Get-ADComputer (PS ver 2.0).

PS:\> $(Get-ADComputer 'mycomputer').distinguishedName

, $env: COMPUTERNAME.

+4

ADSIsearcher. (, , ), . AD , ComputerName. , , .

, , , .

+1

Try something like this:

$de = New-Object System.DirectoryServices.DirectoryEntry
$ds = New-Object System.DirectoryServices.DirectorySearcher
$ds.SearchRoot = $de
$ds.Filter = "(&(objectCategory=computer)(objectClass=computer)(samAccountName=$($env:ComputerName)$))"
$ds.SearchScope = "SubTree"

$r = $ds.FindOne()

$r.Path
0
source

Try it ... Easy to understand and easy to remember ...

$cn = Read-Host Enter ComputerName

$cnObj = Get-ADComputer $cn

$ou = $cnObj.distinguishedname

$ou

0
source

The only reliable way to find out the DistinguishedName of a computer is the following method, which must be run as administrator:

gpresult /r /scope:computer | find "CN="
0
source

I think you can get it from the environment using:

$computer = gc env:computername

Or is this exactly what you do not want? I am terrible with powershell.

-1
source

All Articles