PowerShell Select-String from file with Regex

2019-05-04 21:54发布

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).

2条回答
聊天终结者
2楼-- · 2019-05-04 22:22

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('"'))
查看更多
孤傲高冷的网名
3楼-- · 2019-05-04 22:30

The following gets everything between " and proj":

$sln = Get-Content $PathToSolutionFile
$sln | Select-String ', "([^\\]*?\\)?([^\.]*\..*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.

查看更多
登录 后发表回答