Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

Using Regex to match a path in Powershell

I wanted to use Powershell's Regex to match a specific string in a path. I then want to pipe that into Get-FileHash and get the MD5 hashes of all the files.

The path can change, depending on where the user has these files. So for instance, it can be

C:Program FilesStackOverflowPowershellRegex

or

C:StackOverflowPowershellRegex

I want to make it so that only the Regex portion is selected which I can then -Recurse and pipe into Get-FileHash. Also please note that there can be subfolders inside of Regex (for instance: /Regex/Folder1 and /Regex/Folder2)

I can't quite get how to go about it. Please help me with this, thank you.

question from:https://stackoverflow.com/questions/65559758/using-regex-to-match-a-path-in-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A regex is not needed. There's Split-Path that parses paths and returns desired sections.

For example (this is on MacOS, should work the same on Windows)

PS >pwd
/Users/myHomeDir

PS >pwd | split-path -leaf
myHomeDir

Also, a string that contains a path can be processed. Like so,

$p = "C:Program FilesStackOverflowPowershellRegex"
split-path -leaf $p
Regex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...