Try {
$InDepartment = $False
if ((Get-ADuser $user.alias -Properties showInAddressBook) -notmatch “department1″) {
$InDepartment = $True
}
} Catch {
# $user.alias wasn’t found
}
This way, $InDepartment will be $True/$False based on the last user you checked. If the user doesn’t exist, it’ll run the Catch{} block. You can do whatever you need there. All of this would go inside your existing ForEach loop.
You’ll have to decide what to do with $InDepartment. I don’t know enough about what you’re trying to do to suggest anything.
Reference: about_variables, about_try_catch_finally