Share via

Powershell switch default doesn't work with wildcard

Glenn van Es 21 Reputation points
2021-07-26T19:47:40.143+00:00

I've been fiddling around with the thing below all day, but can't find out why the switch wouldn't work.
Idea is simple, if the username starts with an A we write that it's a match, if it's doesn't we run default and tell that it's not a match.
Would anyone be able to inform me on why this doesn't work? I've went through all the examples, and everything works until I add the -Wildcard.

switch -Wildcard ($env:UserName) { "A*"
{

$env:UserName
write-Host 'Its a match'

}

default {

write-Host 'no match'
$env:UserName
}

}
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Evgenij Smirnov 541 Reputation points
2021-07-26T19:55:32.277+00:00

Hi,

works here. Can you post a sample of the output?

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2021-07-26T20:09:01.553+00:00

    This works:

    "Abc", "XYZ" |
        ForEach-Object{
            Switch -Wildcard ($_) { 
                "A*"    { "$_ : It's a match"; break }
                default { "$_ : no match"; break }
            }
        }
    

    Note the presence of the "break" at the end of each condition! Your code didn't have that so it'll hit the "default" condition even if the "A*" matched.

    Not providing the data you're testing against isn't helpful. Instead of "$_:UserName" try your rest with a known set of string values.

    Was this answer helpful?

    0 comments No comments

  2. Glenn van Es 21 Reputation points
    2021-07-26T20:02:39.72+00:00

    I don't understand, I tested it just now and it didn't work, and now I am running the exact same thing after reopening the file and it works.. I didn't change anything.. Thanks for testing it out anyways, I don't understand why it didn't work, maybe some hidden character or something like that.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.