I'd like to script the management of Docker containers, but I find it difficult to pass PS variables to Docker commands, in particular due to path format differences.
The following line (*) and the likes you can find here do work, however they are inconvenient:
Start-Process docker " run --rm -v $($env:USERPROFILE -replace '\\','/'):/data alpine ls /data"
Indeed, PS Start-Process
is perfect for an MSI installer where you need to see the popup and to control its level of visibility so as to understand that a silent installer is going. Instead, you don't want to start a new window each time you run a console app and particularly in Docker, where you interact back and forth with caller and called shell.
To "Run a command, script, or script block" PS specifically provides &
, "the call operator, also known as the 'invocation operator'". However, I attempted without success with:
& docker run --rm -v $($env:USERPROFILE -replace '\\','/'):/data alpine ls /data
Cmd.exe
would perhaps make things easier, but PowerShell is the official shell to interact with Docker for Windows. Thus, there should be a reliable way to pass variable arguments to Docker commands.
(*) The remove switch -rm
is used here only for the purpose of experimenting with the answer avoiding cluttering your workspace. Of course, I do not usually destroy the container as soon as I create it, but rather interact with it passing -ti
.
EDIT
@AnsgarWiechers proposes parameters splatting in a comment:
$params = 'run', '--rm', "-v $($env:USERPROFILE -replace '\\','/'):/data", 'alpine', 'ls /data'
docker @params
Assuming I am implementing it properly, it doesn't work either and gives:
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: invalid mode: /data.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.