I have a function called tabLength that should return a string.  This is for formatting in a text document.
Could anyone check out my switch statement and see why I am getting an error on line 6. That is the 'case' that the switch statement is going through.
Function tabLength ( $line ) {
    $lineLength = $line.Length
    switch -regex ( $lineLength ) {
        "[1-4]" { return "`t`t`t" }
        "[5-15]" { return "`t`t" }
        "[16-24]" { return "`t" }
        default { return "`t" }
    }
}
Error Message:
Invalid regular expression pattern: [5-15].
At C:\Users\name\desktop\nslookup.ps1:52 char:11
+         "[5-15]" <<<<  { return "" }
    + CategoryInfo          : InvalidOperation: ([5-15]:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression
It is only happening to values being sent through [5-15].
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases).
The syntax of the switch statement is: statement(s); break; case constant 2: statement(s);
A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).
[5-15] is not a valid regex character class. You are matching strings, not numbers, so [5-15] essentially says "match a single character from '5' through '1', or '5'" which is not what you want.
If you remove that middle condition, the [16-24] should fail similarly.
Try a switch statement that doesn't use regex, but uses a script block for conditions so you can use a range to test, like this:
Function tabLength ( $line ) {
    $lineLength = $line.Length
    switch ( $lineLength ) {
        { 1..4 -contains $_ } { return "`t`t`t" }
        { 5..15 -contains $_ } { return "`t`t" }
        { 16..24 -contains $_ } { return "`t" }
        default { return "`t" }
    }
}
In powershell 3+, you could use the -in operator and reverse the order:
Function tabLength ( $line ) {
    $lineLength = $line.Length
    switch ( $lineLength ) {
        { $_ -in  1..4 } { return "`t`t`t" }
        { $_ -in 5..15 } { return "`t`t" }
        { $_ -in 16..24 } { return "`t" }
        default { return "`t" }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With