Adding All Projects To A .NET Solution With Dotnet CLI And PowerShell

I’ve recently spent a bunch of time learning C# and ASP.NET and I often find myself creating multiple projects and wanting to add them all to a Solution with one command rather than individually. I primarily use the dotnet CLI for managing projects and solutions so I worked out a simple way to do this with PowerShell and wanted to share.

So here’s my method using PowerShell’s Resolve-Path:

dotnet sln add (Resolve-Path *\*.csproj)

# Or using the default Resolve-Path alias 'rvpa'
dotnet sln add (rvpa *\*.csproj)

Example

Let’s see a full example:

# Create the solution file
PS C:\Code\Example> dotnet new sln

The template "Solution File" was created successfully.

# Create the projects
# Project 1
PS C:\Code\Example> dotnet new classlib -o Example.Library

The template "Class Library" was created successfully.

Processing post-creation actions...
Restoring C:\Code\Example\Example.Library\Example.Library.csproj:
  Determining projects to restore...
  Restored C:\Code\Example\Example.Library\Example.Library.csproj (in 124 ms).
Restore succeeded.

# Project 2
PS C:\Code\Example> dotnet new console -o Example.Console

The template "Console App" was created successfully.

Processing post-creation actions...
Restoring C:\Code\Example\Example.Console\Example.Console.csproj:
  Determining projects to restore...
  Restored C:\Code\Example\Example.Console\Example.Console.csproj (in 111 ms).
Restore succeeded.

# Add both new projects to the solution
PS C:\Code\Example> dotnet sln add (rvpa *\*.csproj)

Project `Example.Console\Example.Console.csproj` added to the solution.
Project `Example.Library\Example.Library.csproj` added to the solution.

Making it more convenient

Nobody wants to type (rvpa *\*.csproj) every time, so what we can do is create a small function which lives in our PowerShell $Profile, as so:

function all {rvpa *\*.csproj}

We can then do:

PS C:\Code\Example> dotnet sln add (all)

Project `Example.Console\Example.Console.csproj` added to the solution.
Project `Example.Library\Example.Library.csproj` added to the solution.

We could of course create a function that wraps the whole thing, but I prefer this approach as it stays close to the dotnet CLI tool.

You may also wonder what happens if we run this on projects that have already been added to the solution - the answer is nothing at all, the dotnet CLI handles it just fine.

PS C:\Code\Example> dotnet sln add (all)

Solution C:\Code\Example\Example.sln already contains project Example.Console\Example.Console.csproj.
Solution C:\Code\Example\Example.sln already contains project Example.Library\Example.Library.csproj.

That’s it 👍


If you enjoyed this post consider sharing it on , , , or , and .