techdrive
asked on
Powershell if statement question
Whats the best way to write an if statement for this please. I think I might be doing something wrong here with the code.
$mailstats = 5000
IF ($mailstats -GT 6000) {
code injected here
}
Else
IF ($mailstats -GT 4000 -and $mailstats -lt 5999 ) {
code injected here
}
else
if ($mailstats -GT 3000 -and $mailstats -lt 3999 ) {
code injected here
}
$mailstats = 5000
IF ($mailstats -GT 6000) {
code injected here
}
Else
IF ($mailstats -GT 4000 -and $mailstats -lt 5999 ) {
code injected here
}
else
if ($mailstats -GT 3000 -and $mailstats -lt 3999 ) {
code injected here
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Maybe some more notes on this.
To do this in a switch without ranges, the "break" statement is required; in a Switch, Powershell continues to check expressions even after it finds match (except for 'default', which will only be processed if no other expression matched).
To do this in a switch without ranges, the "break" statement is required; in a Switch, Powershell continues to check expressions even after it finds match (except for 'default', which will only be processed if no other expression matched).
$mailstats = 5000
Switch ($mailstats) {
{$_ -gt 6000} {
"$($_) is -gt 6000"
Break
}
{$_ -gt 4000} {
"$($_) is -gt 4000"
Break
}
{$_ -gt 3000} {
"$($_) is -gt 3000"
Break
}
default { ## -le 3000
"$($_) is -le 3000"
}
}
And integer ranges can be specified as <Start>..<End> as well, so if ranges are a must, something like this is easier readable:$mailstats = 5000
If ($mailstats -gt 6000) {
"$($mailstats) is -gt 6000"
} ElseIf ($mailstats -in 4001..6000) {
"$($mailstats) is -in 4001..6000"
} ElseIf ($mailstats -in 3001..4000) {
"$($mailstats) is -in 3001..4000"
} Else {
"$($mailstats) is -le 3000"
}
Both of your scripts will fail for mailstats with sizes of 3999, 4000, 5999, 6000, which is the danger of specifying full ranges.
The correct comparisons would be
if ($mailstats -GT 4000 -and $mailstats -le 6000) {
if ($mailstats -GT 3000 -and $mailstats -le 4000) {