Home > database >  Powershell Delete Computer Object
Powershell Delete Computer Object

Time:01-27

Can some one help me on the next code im trying to run.. it seem's to be ok for me but does not delete the Object when i execute-it

Import-Module ActiveDirectory
Clear-Host
$Computer = Read-Host "Type in the Host to Delete"
$rute = Get-ADComputer -Identity:"CN=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com"


if($rute.Contains($Computer)){
Clear-Host
Remove-ADComputer -Identity=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
#Clear-Host
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5

} else{
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}

try to delete a Active directory object.. expected to work

CodePudding user response:

Your code is not very clear and seems overengineered, $rute.Contains($Computer) will never ever be $true, you probably meant $rute.DistinguishedName.Contains($Computer) which could be $true but .Contains is case-sensitive so it could also be $false.

Your Read-Host statement is assigned to $Computer but then you're using $Computadora. Also, it's unclear why you are hardcoding OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com, I would assume you want to use this OU as your -SearchBase.

Here is how you can approach and will most likely work:

$param = @{
    SearchBase = "OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com"
    LDAPFilter = "(name={0})" -f (Read-Host "Type in the Host to Delete")
    Server     = "DCKABI02.kabi.ads.fresenius.com"
}
$computer = Get-ADComputer @param

if($computer) {
    Clear-Host
    $computer | Remove-ADComputer -Server "DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
    Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
    Start-Sleep -Seconds 5
}
else {
    Clear-Host
    Write-Host "The Host does not exist on AD" -ForegroundColor Red
    Start-Sleep -Seconds 3
}
  • Related