我在沒有連接到域的遠程計算機上運行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