So in the spirit of this short but sweet tutorial I'm trying to filter out disabled user and only work on the "Enabled" users with this code. (FYI Search-ADAccount needs elevated)
$EXPusers = (Search-ADAccount -AccountExpired -UsersOnly)
foreach($user in $EXPusers){
$UENB = $user.Enabled
$UENB # Sanity Check
if($UENB -eq "False"){
continue
}
# All of this is functioning
# disable user
# Logoff user
# Send email
}
In my lab $EXPusers just resolves to one user that is disabled or Enabled=False. So what happens is no matter what I set $UENB equal to it keeps sending mail. Seems to me that if it's "False" it should skip that iteration and not process the rest of the foreach statement and move to the next user, in this case do nothing. What am I missing?
CodePudding user response:
The reason why it's failing is because you're comparing a boolean
(the Enabled
Property of an ADAccount
instance is a bool
) with a string
. It's important to note that, in PowerShell a string that is not empty will always be $true
and, since in your comparison the string is in the right hand side (RHS) of the comparison, PowerShell attempts type coercion as the same type of the left hand side (LHS), so the string 'false'
is converted to a boolean during the comparison which results being $true
.
In about Comparison Operators documentation on the Equality operators section we can read the following:
The equality operator can compare objects of different types. It is important to understand that the value is on the right-hand side of the comparison can be converted to the type of the left-hand side value for comparison.
A simple demo:
[bool] 'false' # => $true
$false -eq 'false' # => $false
'false' -eq $false # => $true
The last comparison results in $true
because the boolean $false
in the RHS is converted to string and, in PowerShell, [string] $false
results in the literal string false
.
In conclusion, by simply changing your if
condition your code would work properly:
if($false -eq $UENB) {
continue
}
The other alternative would be to use the logical -not
operator:
if(-not $UENB) {
continue
}