如何有条件地包括安装卷

时间:2018-07-26 20:47:33

标签: powershell docker

我有一个docker run命令,看起来像这样:

docker run `
-v C:\some\dir:/root/some/dir

我想做的是仅在存在C:\some\dir的情况下包括卷装载,但是我似乎无法正确理解PowerShell语法。

我尝试了以下操作,但一直得到"C:\\some\\dir\\" is not a valid windows path。为了清楚起见,我将使用真实世界的代码。

$awsPath = $null
if(Test-Path ~/.aws) {
   $awsPath = Resolve-Path ~/.aws
   $aws_mount = "-v ${awsPath}:/root/aws"
}

docker run `
$awsPath

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

Docker中的反斜杠字符是转义字符。我认为Docker试图通过添加双斜杠来解决这个问题,以使您能够逃脱反斜杠。在我变通的过程中,幸运的是使用斜杠而不是反斜杠,PowerShell在使用路径名时会理解斜杠。

请参见下面的示例代码:

$awsPath = "c:\temp\aws"

if (Test-Path -Path $awsPath) {
    # Escape the backslash here as the backslash is the escape char in regex also
    $dockerAwsPath = $awsPath -replace "\\", "/" 
    docker run --rm -v ${dockerAwsPath}:/root/aws busybox ls -a /root/aws/
} else {
    docker run --rm busybox ls -a /root
}

输出:

.
..

现在我创建文件夹:

New-Item -Path $awsPath -ItemType Directory | Out-Null
"Hello" | Out-File -FilePath "$awsPath/hello.txt"

if (Test-Path -Path $awsPath) {
    # Escape the backslash here as the backslash is the escape char in regex also
    $dockerAwsPath = $awsPath -replace "\\", "/" 
    docker run --rm -v ${dockerAwsPath}:/root/aws busybox ls -a /root/aws/
} else {
    docker run --rm busybox ls -a /root
}

并输出:

.
..
hello.txt

因此,Powershell / Docker都理解以下路径:

PS C:\temp> $dockerAwsPath
c:/temp/aws

如果使用Dockerfile,则有一些here有关将转义符更改为其他内容的详细信息。我还没有尝试过,但是它可以作为另一个解决方案。