Environment
Windows 11 23H2
Powershell v5.1
Docker desktop 4.49.0
Issue
I have a weird problem when I use variables as arguments for a docker run command inside a Powershell script (.ps1 file).
If I run the command without using variables in a Powershell session, it works fine:
docker run --rm -it -v "//c/host/path:/container/path" my_image
If I run the the same command as above inside a Powershell script, still without using variables, it works fine:
# foo.ps1
docker run --rm -it -v "//c/host/path:/container/path" my_image
The problem comes when I use a variable to store the volume mounting (-v ...):
# foo.ps1
$volume = " -v `"//c/host/path:/container/path`" "
Write-Host docker run --rm -it ${volume} my_image
docker run --rm -it ${volume} my_image
Result of Write-Host (I replaced the host path for security reason, but the path is normal and has no special characters or whatsoever):
docker run --rm -it -v "//c/Users/rest_of_path:/home/ubuntu/ros2_ws" my_image:dev
Result of the docker run command:
docker: Error response from daemon: create /c/Users/rest_of_path: " /c/Users/rest_of_path" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path
In the path I provide, the leading double slash is replaced by a leading blank and a single slash, and that must be the source of the problem. However, I don't know if it is related to Powershell/Windows or Docker, and I haven't found any solutions online.
$volume, not the entire argument? because I think that's the issue.. there are a lot of spaces and quotes in that string currently. I would try:$volume = "//c/host/path:/container/path"anddocker run --rm -it -v $volume my_image.$volume = "-v", "//c/host/path:/container/path". Issue is your variable is interpreted as a single argument instead of 2foo -o "bar baz", use$a = @('-o', 'bar baz'); foo $a. Note: You can not use a single string to encode multiple arguments. See the linked duplicate for details.