Using sc.exe in PowerShell does not create service with quotes

Viewed 39

I try to create a service using PowerShell with following command in PowerShell script (.ps1):

c:\windows\system32\sc.exe create "blaService" displayname= "blaService" binpath= "\"C:\Program Files\xxxx\xxx xxx\xxxxx\xxxxxx.exe\"" start= "auto"

Then I go to the Registry Editor and I see in the ImagePath field (corresponding to the service I've created)enter image description here:

The result I'd expect to get is the same but quoted, so basically "C:\Program Files\xxxx\xxx xxx\xxxxx\xxxxxx.exe"

I followed this thread: When creating a service with sc.exe how to pass in context parameters?

All comments guide to do the same as I did, so I don't understand where am I wrong

1 Answers

A workaround using Start-Process:

#Requires -RunAsAdministrator

$sc_command = 'sc.exe create "blaService" displayname= "blaService" binpath= "\"d:\some path\to some.exe\"" start= "auto"'
$sc_command                              # make public command to process
$null = sc.exe delete blaService 2>$null # ensure that service does not exist
Start-Sleep -Seconds 2                   # give some time to finish

Start-Process -FilePath "$env:comspec" -ArgumentList '/C', $sc_command

Start-Sleep -Seconds 3                   # give some time to finish
                                         # and ensure properly quoted ImagePath
reg.exe query HKLM\SYSTEM\CurrentControlSet\Services\blaService -v ImagePath

Output: D:\PShell\SO\73646083.ps1

sc.exe create "blaService" displayname= "blaService" binpath= "\"d:\some path\to some.exe\"" start= "auto"

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\blaService
    ImagePath    REG_EXPAND_SZ    "d:\some path\to some.exe"

Finally, clear this absurd stuff from the registry:

sc.exe delete blaService

[SC] DeleteService SUCCESS

Related