How can I call sc create from powershell script

I want to call sc create from a powershell script. Here is the code

 function Execute-Command { param([string]$Command, [switch]$ShowOutput=$True) echo $Command if ($ShowOutput) { Invoke-Expression $Command } else { $out = Invoke-Expression $Command } } $cmd="sc create '"$ServiceName'" binpath='"$TargetPath'" displayname='"$DisplayName'" " Execute-Command -Command:$cmd 

which gives the following error:

 Set-Content : A positional parameter cannot be found that accepts argument 'binpath=...'. At line:1 char:1 

What is the problem? What are the positional arguments?

+11
source share
2 answers

The problem here is not in the sc executable. As the error message says, sc resolves to Set-Content . If you run Get-Alias -Name sc , you will see:

gal sc

To bypass the alias, use the full name of the executable file (including the file extension):

 PS C:\> sc.exe query wuauserv SERVICE_NAME: wuauserv TYPE : 20 WIN32_SHARE_PROCESS STATE : 4 RUNNING (STOPPABLE, NOT_PAUSABLE, ACCEPTS_PRESHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 

You might want to use the -f operator when building command-line arguments to avoid the annoying -f quotes everywhere:

 $CmdLine = 'sc.exe create "{0}" binpath= "{1}" displayname= "{2}" ' -f $ServiceName,$TargetPath,$DisplayName Execute-Command -Command $CmdLine 
+20
source

The exact command worked for me from a simple command line console, while it does not work in PowerShell and VS Code Integrated Terminal. In fact, all sc commands had to be run from the command line as administrator.

 sc create MyService binPath= "C:\svc\sampleapp.exe" sc start MyService 
0
source

Source: https://habr.com/ru/post/1236236/


All Articles