简体   繁体   中英

How to use Powershell expression in Powershell command?

On Linux I can run

docker run --volume $(pwd):/some_dir container_image

In Powershell, $pwd doesn't return the path string but instead returns some object. I learned that I can fetch the path by typing $pwd.path . But then this path has backslashes, which docker doesn't like. So I can type $((pwd).path -replace "\\\\", "/") to get the path with forward slashes.

But I now fail to understand how to use this variable in my original docker command.

On Windows, and in Powershell, this doesn't work:

docker run --volume $((pwd).path -replace "\\", "/"):/some_dir container_image

What am I doing wrong?

In Powershell, the $((pwd).path -replace "\\\\", "/") works well, so try to combine it all as a sting you pass as your full path:

docker run --volume ($((pwd).path -replace "\\", "/"))+":/some_dir" container_image

Full disclosure: I'm not famailiar with docker syntax, so can't promise this'll work, but worth a shot, right?

I would try this:

docker run --volume "$((pwd).path -replace '\\', '/'):/some_dir" container_image

Here is the reason:

PS C:\> $((pwd).path):something
At line:1 char:14
+ $((pwd).path):something
+              ~~~~~~~~~~
Unexpected token ':something' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

PS C:\> "$((pwd).path):something"
C:\something

So, if you quote the whole path properly, it should work as you expect it. Because you are using subexpression $() outside a string, ':/somedir' is not part of the path result. They are not automagically joined in linux (bash) shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM