Search code examples
powershelldockerdevopspowershell-coredocker-run

How to execute ps1 script using docker run command?


I need to use the official PowerShell Core Docker image to run a Docker container and make it execute a PowerShell script file.

I know it can be done using a Dockerfile and Docker build, but can't use that in this case.

From reading docs I came up with this, but it does not seem to work:

docker run -it --rm --entrypoint "/tmp/test.ps1" repo/powershell:latest

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/tmp/test.ps1\": stat /tmp/test.ps1: no such file or directory": unknown.
ERRO[0001] error waiting for container: context canceled

Error seems to say that it can't find the file but when running stat "/tmp/test.ps1" manually it works fine.

I feel like the binary pwsh should also be specified but can't find a way how to do it.


Solution

  • docker run -it mcr.microsoft.com/powershell pwsh -c "Write-Host 'Hello, World'"

    this produces Hello, World

    and mcr.microsoft.com/powershell is what google return as official PowerShell Core Docker image

    this image doesn't have file /tmp/test.ps1 inside. so not exactly clear what that image repo/powershell:latest have inside.

    • if you are trying to read a file and execute inside of docker than this worked just fine for me:
    docker run -it --rm mcr.microsoft.com/powershell pwsh -c $(cat test.ps)
    
    • or, if you are trying to pass host file into the container and execute you can map local path to path inside of the container and than it would be:
    docker run -v /tmp/localdata:/tmp/containerdata  -it --rm mcr.microsoft.com/powershell pwsh /tmp/containerdata/test.ps
    

    assuming that you have on host /tmp/localdata folder which contains test.ps file with Write-Host 'Hello, World!' text.

    both ways result is Hello, World