Wildcards in switch strings

Welcome Forums General PowerShell Q&A Wildcards in switch strings

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
4 years, 4 months ago.

  • Author
    Posts
  • #16826

    Participant
    Points: 0
    Rank: Member

    Hi,

    I have got some trouble with the switch statement because I have to check log statements from a logfile.

    The statements could be for example:

    cvs [update aborted]: no such user XYZ
    cvs update: cannot open XYZ
    cvs update: No CVSROOT specified!

    but also...

    ? XYZ
    U XYZ
    M XYZ
    R XYZ

    In the real logfile XYZ is changed by a file- or directory name.

    I'm looking for a simple switch statement for checking the logfile string. My problem is the wildcard symbol "?" that is included in one logfile statement. When I use the -wildcard option for the last 4 examples are the same for powershell.

    Do you have any ideas for me?

    Thanks

  • #16830

    Member
    Points: 0
    Rank: Member

    If you need to match a literal ?, * or square bracket character in a wildcard string, place that character inside a set of square brackets:

    $strings = 'Whatever UXYZ Whatever', 'Whatever ?XYZ Whatever'
    
    switch -Wildcard ($strings)
    {
        '*[?]XYZ*' { "Matched: '$_'" }
    }
    
  • #16832

    Participant
    Points: 0
    Rank: Member

    If the problem is, that the shell takes "?" as a wildcard, but you want it to be a literal "?", you can use the escape character, which is a bactick, just before the "?". Like this: `?
    This way, the shell wont treat "?" as awildcard.
    Is this what you mean?

  • #16849

    Participant
    Points: 0
    Rank: Member

    Yes that is what I mean. Thanks for all the hints. I'll try it.

The topic ‘Wildcards in switch strings’ is closed to new replies.