Pass PowerShell variables to Docker commands

依然范特西╮ 提交于 2019-12-20 02:54:51

问题


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'.                                        

回答1:


There is no need for parameter splatting or even the call operator, double-quoting solves:

docker run --rm -v "$($env:USERPROFILE -replace '\\','/'):/data" alpine ls /data


来源:https://stackoverflow.com/questions/48599026/pass-powershell-variables-to-docker-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!