Samuel Meddows
Samuel Meddows

Reputation: 36712

Searching for backslash in a string with Powershell

I need to search for the amount of backslashes in a string to determine some file path parameters. I have not worked out a way to seach for a backslash without Powershell thinking it is an escapee character.

([regex]::Matches($FilePath, "\" )).count 

Or

$a -match "\"

These both come up with an error "Illegal \ at end of pattern"

Thanks!

Upvotes: 3

Views: 9462

Answers (2)

SurveyLoophole
SurveyLoophole

Reputation: 71

Backslash is an escape character in regex.

Heres's how I did it:

$backslashCount = $FilePath | Select-String -Pattern "\\" -AllMatches
$backslashCount.Matches.Length

Select-String documentation:
Select-String (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn

Upvotes: 0

Jason Boyd
Jason Boyd

Reputation: 7029

You can escape a backslash with a backslash:

[Regex]::Matches($FilePath, "\\").Count

Upvotes: 5

Related Questions