使用自定义 bin 路径/配置通过 PowerShell 创建 MongoDB windows 服务

Creating a MongoDB windows service via PowerShell with a custom bin path / config

我目前在从 powershell 调用 sc.exe 创建调用(创建 windows 服务)时遇到问题。

我正在尝试使用一系列自定义参数为 mongodb 服务创建一个 windows 服务包装器。

$ServiceName = "MyMongoDb"
$DisplayName = "My MongoDb Service"
$mediaPath = "C:\Program Files (x86)\Company\Product"
$ConfigPath = ("{0}\MongoDb\mongod.cfg" -f $mediaPath)
$TargetPath = ("{0}\MongoDb\bin\mongod.exe" -f $mediaPath) 
$cmd = 'sc.exe create "{0}" binpath= ""{1}" --service --config="{2}"" displayname= "{3}" start= "auto"' -f $ServiceName,$TargetPath,$ConfigPath,$DisplayName
iex $cmd | Tee-Object  ("{0}\output.txt" -f $mediaPath) 
Write-Host 'Created Service...'

我遇到的问题是 powershell 失败并出现以下错误 -

x86 : The term 'x86' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path 
is correct and try again.
At line:1 char:56
+ sc.exe create "MyMongoDb" binpath= ""C:\Program Files (x86)\Company\Product\Mong ...
+                                                        ~~~
    + CategoryInfo          : ObjectNotFound: (x86:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

实际上,它不会将 bin 路径视为单个字符串。我试图以各种不同的方式转义字符串,包括使用 ' 和 "" 但无济于事。

如有任何帮助,我们将不胜感激。

TYVM

您的问题是因为您需要嵌套引号 运行从 PowerShell 中调用一个 cmdlet。

最终您尝试使用 sc.exe 创建服务并且您的 bin 参数有空格,因此您必须使用反斜杠转义内部引号 "。More info here

在 cmd 中一切都很好,但你不在 cmd 中,而是在 PowerShell 中。

powershell 处理转义字符的方式与 cmd 略有不同,因此传递给 sc.exe 的内容会因此导致错误,因此您需要从 cmd 运行 它。 (cmd.exe --% /c),我也把整个东西放在一个 HERE-STRING 里面,所以它可以从字面上解释。

$ServiceName = "MyMongoDb"
$DisplayName = "My MongoDb Service"
$mediaPath = "C:\Program Files (x86)\Company\Product"
$ConfigPath = ("{0}\MongoDb\mongod.cfg" -f $mediaPath)
$TargetPath = ("{0}\MongoDb\bin\mongod.exe" -f $mediaPath)  
$cmd = @"
cmd.exe --% /c sc.exe create "$ServiceName" binpath= "\"$TargetPath\" --service --config=\"$ConfigPath\"" displayname= "$DisplayName" start= "auto"
"@
Write-Host $cmd
iex $cmd | Tee-Object  ("{0}\output.txt" -f $mediaPath) 
Write-Host 'Created Service...'