Setting PATH in Dockerfile for Windows containers

At RIGANTI, we use Azure DevOps to run our CI/CD workloads, and because of various requirements from each project, we run the builds in our custom agents.

Some older project still rely on .NET Framework or the old Visual Studio Build tools, so the cleanest way to run these workloads is to run Azure DevOps agent in a Windows container. You can easily install any dependency you need in the operating system, and the nice thing is that NuGet and npm are cached, which significantly decreases the build times.


I needed to install PowerShell 7 because the old Windows PowerShell is missing some features and some scripts in our projects require the new stuff. Our Dockerfile to build the agent container installs Powershell 7 by calling choco install pwsh, but this recently stopped adding the location of pwsh.exe to PATH. So I decided to add it myself, and it showed to be not that trivial as it may seem.

ChatGPT advised to use this in a first shot, which doesn’t work in Windows containers as environment variables work differently on Windows:

ENV PATH="C:\\MyTool\\bin;${PATH}"


After more searching, I found out another solution:

RUN setx path "C:\MyTool\bin;%path%"


This works if you use cmd as your SHELL, but the setx utility has a limit on variable length set to 1024. Windows supports up to 32kB, but it cannot be achieved using this utility.

I found the only working way to switch SHELL to powershell and call [Environment]::SetEnvironmentVariable. It involved some dealing with double quotes, because the Docker tries to split the clause behind the RUN command to arguments using its own algorithm, but you need to pass everything as a single argument to powershell -command xxx.

RUN "[Environment]::SetEnvironmentVariable('PATH', 'C:\Program Files\PowerShell\7'+$env:PATH, [EnvironmentVariableTarget]::Machine)"

Notice the double quotes around the entire RUN argument, and the single quotes inside the Powershell command. Quite counter-intuitive, but it works.

0 Comments

Post comment