1
votes

I am currently having an issue when calling the sc.exe create call (to create a windows service) from powershell.

I am trying to create a windows service wrapper for a mongodb service with a series of custom arguments.

$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...'

The issue that i am having is that powershell is failing with the following error -

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

Effectively, its not treating the bin path as a single string. I have attempted to escape the string in a variety of different ways including using ' and "" but to no avail.

Any help would be appreciated.

TYVM

1

1 Answers

1
votes

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...'