本文介绍了将PowerShell变量传递给Docker命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写Docker容器管理的脚本,但是我发现很难将PS变量传递给Docker命令,特别是由于路径格式的差异。

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"

实际上,PS 启动过程非常适合MSI安装程序,您需要查看弹出窗口并控制其可见性级别,以便了解无提示安装程序正在运行。取而代之的是,您不想每次运行控制台应用程序时都启动一个新窗口,尤其是在Docker中,它与调用程序和被调用shell来回交互。

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 可能会使事情变得更容易,但是PowerShell是与。因此,应该有一种可靠的方式将变量参数传递给Docker命令。

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.

(*)删除开关 -rm 在这里仅用于试验答案以避免混乱的目的您的工作区。当然,我通常不会在创建容器后立即销毁它,而是通过 -ti 与它进行交互。

(*) 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.

编辑

@AnsgarWiechers建议的评论:

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


推荐答案

不需要参数拼写甚至调用运算符,双引号解决:

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

这篇关于将PowerShell变量传递给Docker命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:12