在 powershell 中获取当前计算机的可分辨名称,而不使用 ActiveDirectory 模块

问题描述 投票:0回答:10

我有一个脚本,我需要找到它运行的计算机的完整可分辨名称 (

CN=MyComputer, OU=Computers, DC=vw, DC=local
),但是我不能保证
ActiveDirectory
模块将在运行该脚本的所有计算机上可用在。有没有办法在不使用
Get-ADComputer $Env:COMPUTERNAME
的情况下获取当前计算机的完整可分辨名称?


以防万一这是 XY 问题,我想做的是将计算机移动到特定的 OU,但我需要一种方法来获取我正在运行的计算机的 ASDI 条目。

[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);
}
powershell active-directory
10个回答
14
投票

试试这个(需要 v2):

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

5
投票

小心 ADSIsearcher 方法。如果同一林中的不同域中有两台具有相同名称的计算机(导致我执行返回本文的搜索的问题),则此方法不能保证返回正确的计算机。此方法将简单地在 AD 中搜索具有由 ComputerName 环境变量返回的名称的计算机。如果您处于林中具有多个域的环境中,则需要确保交叉引用计算机加入的域。

主持人,这确实应该是对 Shay Levy 的答案的评论,但我不能发表评论,因为我是新人。


4
投票

cmdlet Get-ADComputer(PS 版本 2.0)可以提供帮助。

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

计算机的名称应该是短名称,例如 $env:COMPUTERNAME。


1
投票

我知道找到计算机的 DistinguishedName 的唯一可靠方法是以下必须以管理员身份运行:

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

0
投票

试试这个...易于理解也易于记忆......

$cn = Read-Host
“输入计算机名称”

$cnObj = Get-ADComputer $cn

$ou = $cnObj.distinguishedname

$ou


0
投票

尝试这样的事情:

$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
投票
Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0" -Name "DNName"

0
投票

因为有时候最简单的答案就是最好的

$(Get-ADComputer -Identity $env:COMPUTERNAME).DistinguishedName

我确信命令选项多年来一直在发展,但对于试图在批处理或远程脚本中获取 DistinguishedName 的人来说,这可能是有益的。


0
投票

ADSystemInfo COM 对象 将正常工作,不需要任何其他模块或启动任何 LDAP 搜索

[System.__ComObject].InvokeMember("ComputerName", [System.Reflection.BindingFlags]::GetProperty, $null, (New-Object -ComObject "ADSystemInfo"), $null)

-1
投票

我认为你可以通过使用以下方式从环境中获取它:

$computer = gc env:computername

或者这正是您不想要的?我对 powershell 很糟糕。

© www.soinside.com 2019 - 2024. All rights reserved.