Search code examples
visual-studiopowershellselect-string

find all VS-projects that compile to a .NET 3.5 console application


I have a deeply nested repository, with lots of Visual Studio projects. I need to find all projects, which have TargetFramework 3.5 and Output Type 'console application'.

I figured out that console applications have this in their csproj-file:

<OutputType>Exe</OutputType>

And applications with a window have this:

<OutputType>WinExe</OutputType>

This allows me find all files with extension csproj, which compile to a console application.

$csproj_ConsoleExes = gci -Recurse *.csproj | select-string "<OutputType>Exe</OutputType>"

What I need to do next: I need to filter only those projects with target-framework 3.5. But since $csproj_ConsoleExes contains search results I don't know how to apply select-string again. select-string only work with input-objects of type FileInfo.

Any help is appreciated.


Solution

  • You can take advantage of Select-String's ability to accept multiple search patterns, which allows you to then use Group-Object to determine all those files where both patterns matched:

    Get-ChildItem -Recurse -Filter *.csproj |
      Select-String -SimpleMatch '<OutputType>Exe</OutputType>',
                                 '<TargetFramework>net35</TargetFramework>' | 
        Group-Object Path |
          Where-Object Count -eq 2 | 
            ForEach-Object Name
    

    The above outputs the full paths of all *.csproj files in which both patterns were found.

    Note:

    • This approach only works if, for each search pattern, at most one line per input file matches, which should be true for .csproj files.

    • See this answer for a solution for cases where this assumption cannot be made.