0
function DeleteADUser ()
{
    $AccountObjectCollection | foreach-object {

    if ($_.ADAccountExists -eq $true)
    {
        write-host "User: $($_.ADAccount) found. Deleting..." -ForegroundColor white
        $User = Get-ADUser -server $domain -Identity $_.ADAccount
        Remove-ADUser $User -server $domain -Confirm:$False
        write-host "User: $($_.ADAccount) deleted. Check again..." -ForegroundColor white
            try {
                Get-ADUser  -server $domain -Identity $_.ADAccount | Out-Null
                write-host "User: $($_.ADAccount) exists. Deletion failed!." -ForegroundColor red
        }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException] {
                $_.ADAccountExists = $false
                write-host "User: $($_.ADAccount) deleted." -ForegroundColor green
        }
    
    }else {write-host "User: $($_.ADAccount) not found." -ForegroundColor green}

    }
}

I have some custom objects in an object array $AccountObjectCollection and try to changes values in my foreach loop on the fly but the line $_.ADAccountExists = $false gets the following exception: ´The property 'ADAccountExists' cannot be found on this object. Verify that the property exists and can be set.´ Thats odd because I'm literally in an IF Statement that only shoots when this specific Value exists and is set to true so I'm propably doing something wrong here. How can I change the value inside the foreach loop?

3
  • Try to use the .keys method; loop through the keys and then access the object via $AccountObjectCollection[$key] Commented Apr 14, 2021 at 7:49
  • 1
    Inside your catch block, $_ refers to an exception object, not the current AD account object piped into your foreach-object loop. Thus, it might be best if you used foreach ($ADObject in $AccountObjectCollection) { ... } and replaced your instances of $_ with $ADObject. Commented Apr 16, 2021 at 1:14
  • @leeharvey1 Thats exactly what I needed to know. Now I understand why it didn't work and fixed it by using your method! Please post your comment as answer, so I can approve it. Commented Apr 16, 2021 at 9:21

1 Answer 1

2

Inside your catch block, $_ refers to an exception object, not the current AD account object piped into your foreach-object loop.

Thus, it might be best if you used:

foreach ($ADObject in $AccountObjectCollection) {
    # ...
} 

...and replaced your instances of $_ inside this foreach block with $ADObject

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.