我在一台未连接到域、没有任何模块且正在运行PS 2.0的远程计算机上运行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
,并且propertylist显示了所有属性,但它不允许我删除该对象。
使用"0"参数调用"DeleteTree"时发生异常:"登录失败:未知的用户名或错误的密码。
在C:\TEMP\Domjoin1.1.ps1:49 char:33$OPath.psbase.DeleteTree<lt<lt;()CategoryInfo:未指定:(:)[],MethodInvocationExceptionFullyQualifiedErrorId:DotNetMethodException
代码:
# Function to get a ADSISearcher and set it to the global-AdsiSearcher
Function ConnectAD ()
{
$domain = new-object DirectoryServices.DirectoryEntry($Ldap,"$domainBob",'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的机器上做这件事时,我会收到一条不同的错误消息:
使用"0"参数调用"DeleteTree"时发生异常:"Access否认。(HRESULT:0x80070005(E_ACCESSDENIED)中的异常)"
我发现了问题。
使用invoke命令时,除非-argumentlist指定,否则不会传输变量。我发现的另一种方法是以下方法,这就是我现在使用的方法,效果很好。
$domain = "DOMAINNAME"
$AdUser = "$domainJoinDom"
$AdPW = "PASSWORD"
$AdPass = convertto-securestring -string $AdPW -AsPlainText -Force
$AdCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdUser,$AdPass
$ThisComputer = $Env:COMPUTERNAME
$RetValue = $true
Function CheckExist ()
{
$ErrorActionPreference = ‘SilentlyContinue’
$Ascriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("get-adcomputer $ThisComputer")
$Ret = Invoke-Command -ComputerName SERVERNAME -ScriptBlock $Ascriptblock -Credential $AdCred
$ErrorActionPreference = ‘Continue’
return $Ret
}
$ExistBefore = CheckExist
if($ExistBefore -ne $null)
{
$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("Remove-ADComputer $ThisComputer")
Invoke-Command -ComputerName SERVERNAME -ScriptBlock $scriptblock -Credential $AdCred
$ExistAfter = CheckExist
if($ExistAfter -ne $null){$RetValue = $false}
}
if($RetValue -ne $false)
{
Add-computer -domainname $domain -credential $Adcred -OUPath "OU=MyOU,DC=DOMAIN,DC=DE"
Restart-Computer -Force
}
如果域控制器运行Windows Server 2008或更高版本,则可以利用PowerShell会话来避免使用ADSI。只需运行以下命令:
Enter-PSSession -ComputerName domaincontroller.test.com -Credential (Get-Credential)
然后运行Import-Module ActiveDirectory
以允许您使用Get-ADComputer
和Remove-ADComputer
。