如何检查域中是否已经存在计算机名称我的脚本在每台电脑中使用



我的脚本在我们网络中的每台电脑中都用来重命名电脑,但我想检查域是否已经存在新名称请帮忙

$Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher
$searcher = [adsisearcher]"(&(objectCategory=computer)(objectClass=computer)(name=$global:NewComputerName))"
$searcher.PropertiesToLoad.AddRange(('name'))
$searchResult = $searcher.FindAll()
if($searchResult.count -eq 1)
{
$Result = $true
}
else
{
$Result = $False
}

所以我用这个来检查的结果是真是假

elseif ($Result -match 'true')
{
$msgBoxInput7 = [System.Windows.Forms.MessageBox]::Show('computer is exist', 'OK')
switch  ($msgBoxInput7) {
'OK' {
$groupbox1.ResumeLayout()
$form1.ResumeLayout()
$form1.add_FormClosed($Form_Cleanup_FormClosed)
}
}
}

请帮我这个代码不工作

尝试使用Get-ADComputer(正如Theo在评论中所说(:

if(get-adcomputer -filter "Name -eq 'nameToFind'"){
"Exists"
}else{
"Not exists"
}

如果您将收到错误,如:

The term 'Get-ADComputer' is not recognized as the name of a cmdlet, function etc..

在使用Import-Module ActiveDirectory执行此命令之前,您需要导入模块

你甚至可能会收到另一个问题:

Get-ADComputer : Unable to find a default server with Active Directory Web Services running

如果是,请添加参数-Server和AD服务器名称,例如:

if(get-adcomputer -Server "DC" -filter "Name -eq 'nameToFind'"){
"Exists"
}else{
"Not exists"

}

相关内容

最新更新