[英]Running executable with command line parameters in PowerShell
这必须是可能的。 我能够在Windows中打开命令提示符并执行以下操作:
<some exe> <some exe command line parameters>
在PowerShell甚至是标准Windows批处理文件中,都必须有等效的方法来执行此操作。 例如,从Windows命令提示符下,我可以使用以下命令启动Docker容器:
docker run –-net=kafka -d –-name=zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0
但是,如果我尝试使用PowerShell这样的操作
& "docker" run –-net=kafka -d –-name=zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0
它失败并出现一般错误:
invalid reference format.
PowerShell可能不适合此类高级用例。 任何建议,将不胜感激!
对于这样的高级用法,是否有更好的脚本语言?
总体而言,PowerShell中的外部程序的调用方式与cmd.exe
中的调用方式相同-有所不同,这是由于PowerShell具有其他元字符(例如$
和@
,但在您的特定情况下它们不起作用。 (您的& "docker" ...
变体原则上也可以使用,但是仅在必须使用带引号或基于变量的命令名称或路径时才需要使用&
)。
问题是您的原始命令行包含两个实例–
( EN DASH, U+2013
),而不是 docker
无法识别的预期ASCII范围-
破折号(连字符) 。
快速发现问题的方法:
# Print the code points of characters outside the ASCII range.
PS> [int[]] [char[]] '& "docker" run –-net=kafka -d –-name=zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0' -gt 127
8211
8211
十进制8211
为十六进制。 0x2013
,连接划线的码点,而常规的代码点-
是45
( 0x2d
)。
所有需要的是取代这些–
与实例-
和,因为docker
不需要被引用,就没有必要对&
):
docker run --net=kafka -d --name=zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0
您自己的答案显示了命令的基于变量的实现,该实现与上面的命令实际上相同 -如果预先知道所有参数,则永远不需要使用变量。
如果确实要使用变量,则对所有参数使用单个数组变量并传递该变量要简单得多:
$dockerExe = 'docker'
$dockerArgs = 'run',
'--net=kafka',
'-d',
'--name=zookeeper',
'-e',
'ZOOKEEPER_CLIENT_PORT=2181',
'confluentinc/cp-zookeeper:4.1.0'
& $dockerExe $dockerArgs
注意:
我认为Start-Process cmdlet将很有用。 ArgumentList可以单引号或双引号。
Start-Process docker -ArgumentList "run –-net=kafka -d –-name=zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0"
Powershell转义有很多复杂性。 我写了这个模块来帮助运行外部命令:
https://github.com/choovick/ps-invoke-externalcommand
演示: https : //terminalizer.com/view/49acb54a979
Install-Module -Name ExternalCommand -Scope CurrentUser
Invoke-ExternalCommand -Command "docker" -Arguments @("run","-d","--name=zookeeper","--net=kafka","-e","ZOOKEEPER_CLIENT_PORT=2181", "confluentinc/cp-zookeeper:4.1.0")
这是操作方法。
$app = 'docker'
$a1 = 'run'
$a2 = '--net=kafka'
$a3 = '-d'
$a4 = '--name=zookeeper'
$a5 = '-e'
$a6 = 'ZOOKEEPER_CLIENT_PORT=2181'
$a7 = 'confluentinc/cp-zookeeper:4.1.0'
& $app $a1 $a2 $a3 $a4 $a5 $a6 $a7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.