Mark Allison
Mark Allison

Reputation: 7228

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

Upvotes: 3

Views: 4815

Answers (2)

Simon B
Simon B

Reputation: 218

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

Upvotes: 1

Persistent13
Persistent13

Reputation: 1562

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

Upvotes: 6

Related Questions