Wednesday, June 5, 2024

Use PowerShell in Visual Studio build events when build Docker image for .Net app

Imagine that we have .NET application and created Docker file for it which often contains build and runtime stages (in this example I use .Net6 but it is also valid for higher versions):

# build stage
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
COPY ...
RUN dotnet restore ...
RUN dotnet publish ...

# runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS final
...

and that our VS solution contains build steps which use PowerShell (assume that it is cross platform PowerShell v.7.x). These steps will run during "dotnet publish" step on build stage. You may face with the following error:

powershell command not found

Quick way to fix it is to use "pwsh" command instead of "powershell". It will work because PowerShell became part of .Net SDK docker images since 3.0 preview like described in the following article: Installing PowerShell with one line as a .NET Core global tool. Note also that .Net SDK images are Linux based where "pwsh" command is usual for running PowerShell.

If because of some reason you don't want to change "powershell" to "pwsh" in the code (e.g. if you need to build apps both on Windows and Linux) you may use the following approach: in Docker file add the following command:

RUN ln -s pwsh /usr/bin/powershell

It will add symlink "powershell" which in turn will run pwsh. After that your powershell commands in build events will work both on Windows and Linux including Docker images.

No comments:

Post a Comment