Run PowerShell Commands in Dockerfile

Q

How to run PowerShell Commands in Dockerfile to change Windows Docker images?

✍: FYIcenter.com

A

When building a new Windows image, you can only run executable programs that are already installed on the image.

A Windows image usually provides programs in the C:\Windows\System32 directory, including two commonly used programs CMD.exe and PowerShell.exe:

C:\Windows\System32\cmd.exe
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

So if you are good at using PowerShell.exe, you can use it to change the Windows image by using the "RUN PowerShell ..." instruction in the Dockerfile.

Since you can not run PowerShell.exe interactively the Dockerfile, you must run PowerShell.exe with its sub-command in a single command line in two formats, like

RUN PowerShell Get-ChildItem
RUN PowerShell -Command Get-ChildItem

1. Enter the following Dockerfile, PowerImage, to modify image with the PowerShell.exe program.

C:\fyicenter> type PowerImage
FROM microsoft/dotnet-samples
ENV HOME="C:\\fyicenter"
RUN PowerShell Get-ChildItem Env:HOME
RUN PowerShell Get-ChildItem Env:PATH
RUN PowerShell -Command Get-ChildItem
ENTRYPOINT PowerShell Write "Hello world!"

2. Build image with the Dockerfile:

C:\fyicenter> docker build --file PowerImage --tag power .

Sending build context to Docker daemon  12.88MB
Step 1/6 : FROM microsoft/dotnet-samples

Step 2/6 : ENV HOME="C:\\fyicenter"

Step 3/6 : RUN PowerShell Get-ChildItem Env:HOME
Name          Value
----          -----
Path          C:\fyicenter

Step 4/6 : RUN PowerShell Get-ChildItem Env:PATH
Name          Value
----          -----
Path          C:\Windows\system32;C:\Windows;C:\Windows\Sys...

Step 5/6 : RUN PowerShell -Command Get-ChildItem
    Directory: C:\app
Mode          Length Name
----          ------ ----
-a----           725 dotnetapp.deps.json
-a----          9216 dotnetapp.dll
-a----           744 dotnetapp.pdb
-a----           154 dotnetapp.runtimeconfig.json
-a----          4608 utils.dll
-a----           712 utils.pdb

Step 6/6 : ENTRYPOINT PowerShell Write "Hello world!"

Successfully built db22ee40cd4c
Successfully tagged power:latest

3. Run the new image:

C:\fyicenter> docker run --name power power
Hello
world!

3. Remove container and image, so we can build it again with same name:

C:\fyicenter>docker rm power
C:\fyicenter>docker image rm power

Ok, we are able to use PowerShell.exe program to modify the Windows image.

 

"openjdk" Docker Image for Windows

Run CMD Commands in Dockerfile

Building Docker Images for Windows

⇑⇑ Docker Container Platform - Tutorials

2022-01-24, 9909🔥, 0💬