Note:
In order to detect the case where $status.Enabled
is not a Boolean (such as $null
, if no .Enabled
property exists), use the following as the first if
conditional:
if ($status.Enabled -isnot [bool]) {
"$date Irgendwas stimmt hier nicht. :-)" | Out-File "$filepath\DisableTapeJobLog.txt" -Append
}
The next section assumes that $status.Enabled
returns a Boolean (bool); the complete if
statement is in the bottom section.
Use ($status.Enabled -eq $false)
or, preferably and more succinctly,
(-not $status.Enabled)
Generally speaking:
There is no need to compare a Boolean value against another value explicitly (see next point), but if you do, and that other value isn't already a Boolean, you need to understand how PowerShell converts it to a Boolean - see next section.
It's best to use Boolean values implicitly in conditionals; that is:
- use
$someBooleanValue
in lieu of $someBooleanValue -eq $true
- use
-not $someBooleanValue
in lieu of $someBooleanValue -eq $false
As an aside: If you already know PowerShell's to-Boolean conversion rules, you can use any value implicitly as a Boolean, simply by using it as-is in a conditional and relying on PowerShell to convert it to a Boolean; e.g.,
$val = 'nonempty string'; if ($val) { 'yes' }
outputs yes
, because any nonempty string is coerced to $true
in a Boolean context (see below).
As for what you tried:
($status.Enabled -eq "False")
Comparing a Boolean value ($true
or $false
) to a string value such as "False"
doesn't work as you might expect:
Due to the LHS being a Boolean, PowerShell coerces the RHS to a Boolean too before comparing, and PowerShell's to-Boolean conversion rules consider any nonempty string to be $true
, irrespective of its value.
That is, [bool] "False"
yields $true
(!), because "False"
is a nonempty string.
Therefore, your comparison is equivalent to $status.Enabled -eq [bool] "False"
, which is the same as $status.Enabled -eq $true
(!), i.e. the opposite of your intent.
See the bottom section of this answer for a summary of PowerShell's to-Boolean conversion rules.
To put it all together:
if ($status.Enabled -isnot [bool]) {
"$date Irgendwas stimmt hier nicht. :-)" | Out-File "$filepath\DisableTapeJobLog.txt" -Append
}
elseif (-not $status.Enabled) {
"$date Der Backup To Tape Job wurde erfolgreich deaktiviert." | Out-File "$filepath\DisableTapeJobLog.txt" -Append
}
else {
"$date Der Backup To Tape Job wurde nicht erfolgreich deaktiviert." | Out-File "$filepath\DisableTapeJobLog.txt" -Append
}