mongodb - 通过 PowerShell 使用自定义 bin 路径/配置创建 MongoDB Windows 服务
问题描述
我目前在从 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
解决方案
Your issue is due to fact you need nested quotes running a cmdlet from PowerShell.
Ultimately you are trying to create a service using sc.exe and your bin parameter has spaces, so you have to escape the inner quotes with backslashes ". More info here
Which is all well and good in cmd but you are not in cmd you are in PowerShell.
The way powershell deals with escapes characters is slightly different to cmd so what is getting passed to sc.exe is causing an error for this reason, so you need to run it from cmd. (cmd.exe --% /c), I have also put the whole thing inside a HERE-STRING so it can be interpreted literally.
$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...'
推荐阅读
- python - 如何使该机器人可以在任务管理器中工作?
- wpf - 自定义绘制复选框时,如何将椭圆形的填充颜色绑定到复选框的前景?
- android - 配置项目 ':app' 时出现问题。在 react-native 中并给出一些字节码作为错误
- php - LARAVEL - 我想从包含主类别 ID 的上部 _id 列的类别对象访问主类别
- ruby - 将数组字符串对象转换为哈希?
- grep - 如何使用 zgrep 在归档文件中查找与给定文件名模式匹配的内容?
- angular - 使用 Angular AOT 构建失败
- laravel - 如何在 Laravel Eloquent 中的 take() 之后 orderBy()
- python - 单击提交时,UpdateView 和 DeleteView 导致错误 405
- ios - SwiftUI / iOS | 在没有 NSNotification 的情况下获取键盘大小