Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell switch statement with conditionals

How to have conditionals in a PowerShell switch statement? This code below returns 0 when it should return 1000.

$UsedSpaceMB = 8500

switch ($UsedSpaceMB) {
    ($UsedSpaceMB -gt 15000) { $FreeSpace = 2000 }
    ($UsedSpaceMB -in 8000..15000 ) { $FreeSpace = 1000 }
    ($UsedSpaceMB -in 1700..8000 ) { $FreeSpace = 500 }
    ($UsedSpaceMB -in 1000..1700 ) { $FreeSpace = 200 }
    ($UsedSpaceMB -in 800..1000 ) { $FreeSpace = 100 }
    ($UsedSpaceMB -lt 800 ) { $FreeSpace = 50 }
}
$FreeSpace
like image 750
Mark Allison Avatar asked Feb 11 '26 20:02

Mark Allison


2 Answers

The syntax is incorrect for a switch. Please see here for the documentation.

$UsedSpaceMB = 8500

switch ($UsedSpaceMB) {
    {$_ -gt 15000} { $FreeSpace = 2000 }
    {$_ -in 8000..15000 } { $FreeSpace = 1000 }
    {$_ -in 1700..8000 } { $FreeSpace = 500 }
    {$_ -in 1000..1700 } { $FreeSpace = 200 }
    {$_ -in 800..1000 } { $FreeSpace = 100 }
    {$_ -lt 800 } { $FreeSpace = 50 }
}
$FreeSpace
like image 81
Persistent13 Avatar answered Feb 13 '26 16:02

Persistent13


or you could use -contains

switch ($UsedSpaceMB) {
    {$_ -gt 15000} { $FreeSpace = 2000 }
    {8000..15000 -contains $_ } { $FreeSpace =1000 }
    {1700..8000 -contains $_} { $FreeSpace = 500 }
    {1000..1700 -contains $_ } { $FreeSpace = 200 }
    {800..1000 -contains $_ } { $FreeSpace = 100 }
    {$_ -lt 800 } { $FreeSpace = 50 }
}
$FreeSpace
like image 37
Simon B Avatar answered Feb 13 '26 16:02

Simon B