我在没有连接到域的远程计算机上运行Powershell,没有任何模块并且正在运行PS 2.0。如何从Active Directory远程删除AD计算机 - Powershell
我想联系我的域的Active Directory,检查是否有这台计算机的条目;如果是,请删除该条目。
通过ADSI检查AD是否存在计算机很容易。但是,删除不起作用。
这是到目前为止我的代码:
# Variables
$domain = "Test.com"
$Ldap = "LDAP://$domain"
$Global:AdsiSearcher = $Null
# Function to Delete PC
Function DeleteThisPc()
{
$CurrentSearch = $Global:AdsiSearcher
$One = $CurrentSearch.FindOne()
$OPath = [adsi]$One.Path
$OPath.psbase.DeleteTree()
问题就出在这里。尽管$ OPath类型为System.DirectoryServices.DirectoryEntry
,而属性列表显示了所有属性,但它不允许我删除该对象。
异常调用 “DeleteTree” 与 “0” 的参数(一个或多个):“登录失败: 未知的用户名或密码错误
在C:\ TEMP \ Domjoin1.1.ps1:49炭:33 $ OPath.psbase.DeleteTree < < < <() CategoryInfo:NotSpecified:(:) [],MethodInvocationException FullyQualifiedErrorId:DotNetMethodException
代码:
# Function to get a ADSISearcher and set it to the global-AdsiSearcher
Function ConnectAD()
{
$domain = new-object DirectoryServices.DirectoryEntry($Ldap,"$domain\Bob",'1234')
$filter = "(&(objectCategory=computer)(objectClass=computer)(cn=$ComputerName))"
$AdsiSearch = [adsisearcher]""
$AdsiSearch.SearchRoot = $domain
$AdsiSearch.Filter = $filter
$Global:AdsiSearcher = $AdsiSearch
}
# Main Function
Function Sub_Check-ADComputer()
{
ConnectAD
$CurSearch = $Global:AdsiSearcher.findOne()
if($CurSearch -ne $null)
{
DeleteThisPc
}
}
# Start
Sub_Check-ADComputer
即使问题似乎为错误状态是显而易见的:
登录失败:未知的用户名或密码错误。
用户名和密码与我用于首先从AD获取对象的用户名和密码相同。所以它确实有效 - 当我尝试deleteTree()
时,我不知何时必须再次提供凭证?我还介绍了OU用户FullControl的对象存储在
编辑:
当我和PS 3.0做的另一台机器上,我得到一个不同的错误信息:
异常呼唤 “DeleteTree” 和 “0” 的说法(S): “访问被 拒绝(从HRESULT异常:0X80070005(E_ACCESSDENIED))”。
这似乎是一个非常好的方法。使用我的域管理员帐户,我可以远程运行来自域外的脚本。谢谢! - 一个问题仍然存在,即在使用我创建的服务帐户时,它仍然给我一个“访问被拒绝”。你有没有可能知道服务帐户需要运行这种脚本的哪些组或权利? – Asharon
您的服务帐户需要在相关组织单位上创建/删除计算机对象。您可以使用“Active Directory用户和计算机”管理控制台中的“委派控制向导”。 https://technet.microsoft.com/en-us/library/cc732524.aspx – Christophe