Reputation: 4129
I am trying to retrieve the guids
of projects within a .sln
file using regular expressions
So, for instance, if I have in the file a project like this:
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SomeProject", "SomeProject\SomeProject.csproj", "{F5EF941A-49AD-404D-9EB1-209A75D4113F}"
EndProject
I would do something like this in my script:
$projectsInSolution = Select-String "$file" -pattern 'Project'
$lineProjectsInFile = $projectsInSolution -match " `"{\S*}"
In the regular expression, I leave the whitespace because the real guid is F5EF941A-49AD-404D-9EB1-209A75D4113F
However, when I run this, I get
C:\...\...\...\....sln:6:Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SomeProject",
"SomeProject\SomeProject.csproj", "{F5EF941A-49AD-404D-9EB1-209A75D4113F}"
Why I am not getting the guid only?
I tested it in regexr.com and it seems so be working
Thank you
Edit
This is what I am doing now. But, not getting anything
$projectsInSolution = Select-String "$solutionFileStr" -pattern 'Project'
$lineProjectsInFile = $projectsInSolution -match "(?<={)[^}]+(?=}`"\s*EndProject)"
ForEach($line in $lineProjectsInFile)
{
Write-Output "$line"
}
Upvotes: 1
Views: 218
Reputation: 627537
You may use the following regex:
{(?<GUID>[^}]+)}[^{}]*$
See demo
Then you need to access it the following ways:
$projectsInSolution = Select-String "$solutionFileStr" -pattern '^Project'
$guids = $projectsInSolution.line -match "({(?<GUID>[^}]+)}[^{}]*$"
Perhaps, this will be enough:
select-string -path <file_path> -pattern '({(?<GUID>[^}]+)}[^{}]*$' -allmatches |
foreach-object {$_.matches} |
foreach-object {$_.groups[1].value} |
Select-Object -Unique
Upvotes: 0
Reputation: 175085
You could use a capture group:
$Pattern = '\{(?<RealGuid>[0-9A-F]{8}([0-9A-F]{4}){3}[0-9A-F]{12})\}"$'
$RealGuid = Get-Content -Path $file | ForEach-Object {
if($_ -match $Pattern){
$Matches['RealGuid']
}
}
Upvotes: 0
Reputation: 36342
I think your issue isn't with your RegEx but with how you're running it. Your Select-String
command outputs a Microsoft.PowerShell.Commands.MatchInfo
object, so what you're going to want to match against for that is the Line
property. Also, if all you want is the GUID, I would use -Replace, and make the GUID a capture group, and replace the entire line with just the capture group. Something like this:
$file = 'c:\temp\test.txt'
$projectsInSolution = Select-String "$file" -pattern '^Project'
$lineProjectsInFile = $projectsInSolution.line -replace "^.+ `"{(\S*)}.*$", '$1'
That will result in $lineProjectsInFile
containing an array of strings that are just the project GUIDs.
Upvotes: 3