1

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

  • Why not use PowerShell's New-Service cmdlet? https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-7.2 – endurium Sep 08 '22 at 10:24
  • @endurium It's fine, but I also use `sc.exe failure`. What is the equivalent? `c:\windows\system32\sc.exe failure "xxxx" reset= 5 actions= restart/5000` – Seydou Doumbia Sep 08 '22 at 11:12

2 Answers2

0

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

JosefZ
  • 28,460
  • 5
  • 44
  • 83
0

It appears that escaping quotes is quite challenging there, but this works from PowerShell. Inner quotes are represented with 6 " signs.

sc.exe config "Grafana Agent" binpath= """""""C:\Program Files\Grafana Agent\grafana-agent-windows-amd64.exe"""""" -config.file=""""""C:\Grafana-Agent\grafana-agent-config.yaml"""""" -server.http.address=""""""0.0.0.0:12345"""""""
Alex
  • 1
  • 1