PowerShell 7 – 如何在Windows上运行命令?

huangapple go评论60阅读模式
英文:

PowerShell 7 - how to run a command on windows?

问题

我只想从PowerShell 7脚本中使用参数运行docker命令。当我只使用以下命令时,它可以正常工作:

if ($isRunning -eq $false) {
   docker run -it --rm -p 8080:8080 -v <some_path> <image_name>
}

但我需要在此命令中使用变量,所以我将它更改为:

&amp; "docker run -it --rm -p 8080:8080 -v $script:myPath\:/usr/local/whatever"

它可以运行,但然后告诉我“未将术语'docker run -it ...'识别为cmdlet的名称...”。看起来PowerShell脚本与cmd不具有相同的$PATH环境变量值。

这里有什么问题?

英文:

I just want to run a docker command with parameters from PowerShell 7 script. When I just use the command:

if ($isRunning -eq $false) {
   docker run -it --rm -p 8080:8080 -v &lt;some_path&gt; &lt;image_name&gt;
}

it works. But I need to use a variable in this command, so I changed it to:

&amp; &quot;docker run -it --rm -p 8080:8080 -v $script:myPath\:/usr/local/whatever&quot;

And it runs but then it tells me The term 'docker run -it ...' is not recognized as a name of a cmdlet.... It seems like PowerShell script does not have the same $PATH environment variable value as cmd.

What's wrong here?

答案1

得分: 1

以下可能有效,将参数作为参数数组传递给您的 docker 命令,而不是嵌入在字符串中的表达式,目前失败是因为 PowerShell 正试图查找整个表达式的命令(docker run -it ...)。

if (-not $isRunning) {
    docker @(
        'run'
        '-it'
        '--rm'
        '-p'
        '8080:8080'
        '-v'
        "$script:myPath:/usr/local/whatever"
    )
}
英文:

The following might work, passing the arguments to your docker command as an array of arguments instead of embedding all the expression in a string which is currently failing because PowerShell is trying to find a command with the name of the entire expression (docker run -it ...).

if (-not $isRunning) {
    docker @(
        &#39;run&#39;
        &#39;-it&#39;
        &#39;--rm&#39;
        &#39;-p&#39;
        &#39;8080:8080&#39;
        &#39;-v&#39;
        &quot;$script:myPath\:/usr/local/whatever&quot;
    )
}

huangapple
  • 本文由 发表于 2023年5月22日 23:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定