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?
catchblock,$_refers to an exception object, not the current AD account object piped into yourforeach-objectloop. Thus, it might be best if you usedforeach ($ADObject in $AccountObjectCollection) { ... }and replaced your instances of$_with$ADObject.