简体   繁体   中英

PowerShell Select-String from file with Regex

I am trying to get a string of text from a .sln (Visual Studio solution file) to show what project files are contained within the solution.

An example line of text is

Project("{xxxx-xxxxx-xxxx-xxxx-xx}") = "partofname.Genesis.Printing", "Production\\partofname.Genesis.Printing\\partofname.Genesis.Printing.csproj", "{xxx-xxx-xxx-xxx-xxxx}" EndProject

The part of the string that I am interested in is the last part between the \\ and the " .

\\partofname.Genesis.Printing.csproj"

The regular expression I am using is:

$r = [regex] "^[\\]{1}([A-Za-z.]*)[\""]{1}$"

I am reading the file content with:

$sln = gci .\Product\solutionName.sln

I don't know what to put in my string-select statement.

I am very new to PowerShell and would appreciate any and all help...

I did have a very very long-hand way of doing this earlier, but I have lost the work... Essentially it was doing this for each line in a file:

Select-String $sln -pattern 'proj"' | ? {$_.split()}

But a regular expression would be a lot easier (I hope).

The following gets everything between " and proj" :

Select-String -Path $PathToSolutionFile ', "([^\\]*?\\)*([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} | 
       Foreach-Object {$_.Groups[2].Value}

The first group gets the folder that the proj file is in. The second group gets just was you requested (the project file name). AllMatches returns every match, not just the first. After that it's just a matter of looping through each collection of matches on the match objects and getting the value of the second group in the match.

Your Script works great. To make into a one liner add -Path on the Select String:

Select-String -path $pathtoSolutionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -
AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[2].Value}

To build from this you can use Groups[0]

(((Select-String -path $pathtoSoultionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} | 
       Foreach-Object {$_.Groups[0].Value})-replace ', "','.\').trim('"'))

对我来说,这种模式是最好的: [^"]+\\.csproj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM