I don't know powershell specifics for regex or to scan a file line by line, but assuming powershell regex is like all other regex, the actual pattern to match your string with, looks something like this (the 3rd regex below matches your examples):
^[^\\]*(\\[^\\]*){3}$
- exactly 3 backslashes separated by any number (including zero) of non-backslashes. Note that as backslash is a special character in most regex implementations you probably need to double it, even inside [ ], since it can be used there as well, to match character classes such as [\s]
.
^[^\\]*(\\[^\\]+){,2}$
- between 0 and 2 backslashes and no more, separated by 1 or more of non-backslashes, and with other non-backslash characters after the last backslash.
^[a-z]:\\share\\[^\\]+$
- I think this is what you asked for. Matches the entire string (^ ... $
) to a drive letter followed by "share" followed by a filename, but no further backslashes after the share name. You'd have to add /i
for case insensitive matching, or whatever syntax powershell uses to ignore case, which I don't know, but Google will show how to do that. Replace [a-z]:
by c:
if you definitely know the drive and want it fixed. Replace \\share\\[^\\]+
by (\\[^\\]+){2}
to allow any share name but nothing deeper than the top level. Replace share
by (this-share|that_share)
to allow a list of specific share names.
The second pattern works like this (the third pattern is similar):
^
Match start of string (if we don't test the whole string it might match a portion with 2 backslashes and not check the rest doesn't have more backslashes)
[^\\]*
Match any number (0+) of non backslashes
(\\[^\\]+){,2}
Match a group repeatedly, where the group contains backslash followed by any number >0 of non-backslashes, the group can be repeated up to 2 times (but not more). Use {2}
for exactly 2 matches, or {1,2}
for between 1 and 2 inclusive matches
$
Match end of string - nothing else should be present after the repeats of backslash and non-backslashes are matched (as this last bit will be a filename in your share)
With luck you can work it out from these. It's hard to say more or give a definitive answer as it stands, because there are patterns where you haven't said what it should do. For example, trailing backslashes can be present sometimes, as this is valid and optional if the input happens to be a folder, and could cause the regex to be mis-evaluated for some folders. Ditto for UNC shares such as \\?\D:\share\myfile.txt or \\server\share\myfile.txt, and ditto for paths with just one slash (c:\myfile.text). Ditto for illegal characters (could the file contain anything that isn't a valid filename, such as semicolon, or will you test this separately if it could happen?).
If you clarify more exactly what the regex should do, or if you need an explanation of how these work, I'll update this answer and add a regex or more details.