Modifying the "Path to executable" of a windows service - windows

I'd like to modify the path to my application, but doing so breaks it because the service still points to the old location.
By going to Administrative Tools > Services you can open a properties dialog and view the Path to executable, but there is no way to change it.
Is there any way a user can modify the service path without having to reinstall the application ?

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:
sc config <service name> binPath= <binary path>
Note: the space after binPath= is important. You can also query the current configuration using:
sc qc <service name>
This displays output similar to:
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: ServiceName
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Services\ServiceName
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : <Display name>
DEPENDENCIES :
SERVICE_START_NAME : user-name#domain-name

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services. Find the service you want to redirect, locate the ImagePath subkey and change that value.

You could also do it with PowerShell:
Get-WmiObject win32_service -filter "Name='My Service'" `
| Invoke-WmiMethod -Name Change `
-ArgumentList #($null,$null,$null,$null,$null, `
"C:\Program Files (x86)\My Service\NewName.EXE")
Or:
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
-Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"

Open Run(win+R) , type "Regedit.exe" , to open "Registry Editor", go to
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services
find "Apache2.4" open the folder find the "ImagePath" in the right side, open "ImagePath"
under "value Data" put the following path:
"C:\xampp\apache\bin\httpd.exe" -k runservice foe XAMPP for others point to the location where Apache is installed and inside locate the bin folder "C:(Apache installed location)\bin\httpd.exe" -k runservice

Slight modification to this #CodeMaker 's answer, for anyone like me who is trying to modify a MongoDB service to use authentication.
When I looked at the "Path to executable" in "Services" the executed line already contained speech marks. So I had to make minor modification to his example.
To be specific.
Type Services in Windows
Find MongoDB (or the service you want to change) and open the service, making sure to stop it.
Make a note of the Service Name (not the display name)
Look up and copy the "Path to executable" and copy it.
For me the path was (note the speech marks)
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg" --service
In a command line type
sc config MongoDB binPath= "<Modified string with \" to replace ">"
In my case this was
sc config MongoDB binPath= "\"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe\" --config \"C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg\" --service -- auth"

You can't directly edit your path to execute of a service. For that you can use sc command,
SC CONFIG ServiceName binPath= "Path of your file"
Eg:
sc config MongoDB binPath="I:\Programming\MongoDB\MongoDB\bin\mongod.exe --config I:\Programming\MongoDB\MongoDB\bin\mongod.cfg --service"

i just felt like adding for Git Bash users you should put the path in single quotes ' ' as in
sc config <service name> binPath='<binary path>'
in e.g. sc config MongoDB binPath='"C:\Program Files\MongoDB\Server\5.03\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\5.03\bin\mongod.cfg" --service --auth'
this worked for me to update the path of the service with Git Bash on Windows 10

If you have Process Hacker installed, you can use it.

An alternative to using Invoke-WmiMethod is to use the newer CIM cmdlets. This also avoids the need for the #($null,$null...) object, as seen in a previous answer.
Get-CimInstance win32_service -Filter "Name='My Service'" | Invoke-CimMethod -MethodName Change -Arguments #{PathName="C:\Program Files\My Service\NewName.exe"}

A little bit deeper with 'SC' command, we are able to extract all 'Services Name' and got all 'QueryServiceConfig' :)
>SC QUERY > "%computername%-services.txt" [enter]
>FIND "SERVICE_NAME: " "%computername%-services.txt" /i > "%computername%-services-name.txt" [enter]
>NOTEPAD2 "%computername%-services-name.txt" [enter]
Do 'small' NOTEPAD2 editing..
Then, continue with 'CMD'..
>FOR /F "DELIMS= SKIP=2" %S IN ('TYPE "%computername%-services-name.txt"') DO #SC QC "%S" >> "%computername%-services-list-config.txt" [enter]
>NOTEPAD2 "%computername%-services-list-config.txt" [enter]
Raw data is ready for feeding 'future batch file' so the result is look like this below!!!
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
| SERVICE_NAME | TYPE | START_TYPE | ERROR_CONTROL | BINARY_PATH_NAME | LOAD_ORDER_GROUP | TAG | DISPLAY_NAME | DEPENDENCIES | SERVICE_START_NAME |
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
+ WSearch | 10 WIN32_OWN_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\SearchIndexer.exe /Embedding | none | 0 | Windows Search | RPCSS | LocalSystem |
+ wuauserv | 20 WIN32_SHARE_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\svchost.exe -k netsvcs | none | 0 | Windows Update | rpcss | LocalSystem |
But, HTML will be pretty easier :D
Any bright ideas for improvement are welcome V^_^

The best way for this scenario is to uninstall the application and reinstall the application. That is the right legal way.

You can delete the service:
sc delete ServiceName
Then recreate the service.

Related

How to query and add (if not listed) a location to Windows 10 Search Index using PowerShell

I have to re-mount removable drives (which require authentication) each time I boot the computer and Windows Indexing keeps removing the removable drives (perhaps because the removable drives are not available when the computer boots). In an ideal world Windows Indexing would keep these locations and just list them as 'Unavailable' (which it sometimes does). However because it doesn't I am interested in executing a script that queries the Windows Indexing locations and if it does not list the removable drives then add them. At the bottom of this thread I pasted the Batch script that I setup to run at boot (via Start Up folder) to search for a specific folder that is available thereafter mounting one of the removable drives.
I have found several examples of how to do this on Windows 7 (links pasted below) but I can't figure out how to do it in Windows 10. The links provided to the DLL (Microsoft.Search.Interop.dll) no longer resolve.
When searching for the latest Windows Search SDK for Windows 10 I was lead to the Windows SDK here:
https://learn.microsoft.com/en-us/windows/win32/search/-search-developers-guide-entry-page
I installed the C++ related portion of the Windows SDK then searched for Microsoft.Search.Interop.dll but I couldn't find it. Perhaps the DLL has changed?
From How to rebuild Windows Search Index by using PowerShell?
Load DLL containing classes & interfaces
Add-Type -path "C:\Temp\SearchIndexSdk\Microsoft.Search.Interop.dll"
#Provides methods for controlling the Search service. This
interface manages settings and objects that affect the search engine
across catalogs.
https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
#Retrieves a catalog by name and creates a new ISearchCatalogManager
object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")
#Resets the underlying catalog by rebuilding the databases and performing a full indexing.
#https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()
From How to add a location to windows 7/8 search index using batch or vbscript?
#Code copied from "Powershell Tackles Windows Desktop Search" http://powertoe.wordpress.com/2010/05/17/powershell-tackles-windows-desktop-search/
#Microsoft.Search.Interop.dll is needed, download from http://www.microsoft.com/en-us/download/details.aspx?id=7388
#Load the dll
Add-Type -path "D:\Unattend\UserFiles\Tools\Microsoft.Search.Interop.dll"
#Create an instance of CSearchManagerClass
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
#Next we connect to the SystemIndex catalog
$catalog = $sm.GetCatalog("SystemIndex")
#Get the interface to the scope rule manager
$crawlman = $catalog.GetCrawlScopeManager()
#add scope
$crawlman.AddUserScopeRule("file:///D:*",$true,$false,$null)
$crawlman.SaveAll()
I would add a comment to the existing threads but I am not able to because I don't have reputation of 50 (dumb rule IMO).
Last... I found this site which lists the DLL along with some code but it hasn't been updated in a long time.
https://github.com/FileMeta/WindowsSearchSample
Thanks in advance!
Batch script that runs at boot:
#echo off
echo Windows Search is being restarted to recognize the Z drive
:while
if EXIST Z:\Watch (
I WANT TO CALL POWERSHELL SCRIPT TO ADD THE LOCATION TO THE INDEX IF NEEDED HERE
sc stop WMPNetworkSvc
ping 127.0.0.1 -n 5 > nul
sc stop WSearch
ping 127.0.0.1 -n 5 > nul
sc start WSearch
ping 127.0.0.1 -n 5 > nul
sc start WMPNetworkSvc
echo Exiting this script in 5 seconds
ping 127.0.0.1 -n 5 > nul
exit
) else (
echo Waiting 60 seconds to check if Z drive is available
ping 127.0.0.1 -n 60 > nul
goto :while
)
When I do a search for Searchdll in what I believe to be the folder where the Windows SDK installed to (C:\Program Files (x86)\Windows Kits\10) I find the following. If I had to guess which DLL is the Windows 10 equivalent of Windows 7's Microsoft.Search.Interop.dll I would guess that it's the 1st one i.e. interop.searchapi.dll.
Add-Type -Path "C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64\interop.searchapi.dll" does return without error... however $sm = New-Object Microsoft.Search.Interop.CSearchManagerClass returns with error that it cannot find the class in the assembly.
When I cd to "C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64" and enter ([appdomain]::currentdomain.GetAssemblies() | Where-Object Location -Match 'interop.searchapi').gettypes() I get the following
When I enter (([appdomain]::currentdomain.GetAssemblies() | Where-Object location -match 'interop.searchapi.dll').gettypes() | Where-Object name -eq 'CSearchManagerClass').getmembers() | Format-Table name, membertype I get
From the list of commands in the previous threads I do see GetCatalog and I presume that the members GetCrawlScopeManager, AddUserScopeRule, Reset, and SaveAll exist.
I don't know how to find the fully qualified class name or I'm doing something else wrong (unknowingly).
When I enter ([appdomain]::currentdomain.GetAssemblies() | Where-Object Location -Match 'interop.searchapi').fullname I get the following
Interop.SearchAPI, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
But when I enter $sm = New-Object Interop.SearchAPI.CSearchManagerClass I get an error that it can't find the type Interop.SearchAPI.CSearchManagerClass.

Is there any method for getting details of all installed apps in a Windows device using shell commands

I need to get all installed applications and its details in a Windows device using shell commands. I tried using
Get-appxpackage
Get-WmiObject
wmic
Apps that were installed manually seems to be missing in the list. Please help by providing a better method.
An alternative can be to query the registry like this for example:
# HKLM - Local Machine
$InstalledSoftware = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
foreach($obj in $InstalledSoftware){write-host $obj.GetValue('DisplayName') -NoNewline; write-host " - " -NoNewline; write-host $obj.GetValue('DisplayVersion')}
# HKCU - Current User
InstalledSoftware = Get-ChildItem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
foreach($obj in $InstalledSoftware){write-host $obj.GetValue('DisplayName') -NoNewline; write-host " - " -NoNewline; write-host $obj.GetValue('DisplayVersion')}
Check this page out for more:
https://www.codetwo.com/admins-blog/how-to-check-installed-software-version/
Tip! Browse these locations in the registry manually before you dig in as it will help you see the structure and understand what properties are available. If the information you're seeking is not there, you might just ditch this suggestion.
For Windows 64-bit and 32-bit apps use
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table > C:\ws\apps.txt
the C:\ws\apps.txt need to be adjusted by you, to your output path.
I found the idea here, Social MS

VeraCrypt Windows commandline - encrypt whole USB

I'm trying to format whole USB from windows commandline.
In Linux it's quite easy - veracrypt --create diskPath
But when i'm trying to do that in windows it's impossible.
I'm trying to use this command
"VeraCrypt Format.exe" /create \\?\Volume{ad4200bf-2236-11e8-9b79-bcee7b594766}\ /password test /size 100M
Also this:
"VeraCrypt Format.exe" /create F: /password test /size 100M
Also - i want to encrypt whole partition, not only 100M, but i can't execute /craete without /size
VeraCrypt format command goes like this:
"VeraCrypt Format.exe" [/n] [/create] [/size number[{K|M|G|T}]] [/p
password] [/encryption {AES | Serpent | Twofish | AES(Twofish) |
AES(Twofish(Serpent)) | Serpent(AES) | Serpent(Twofish(AES)) |
Twofish(Serpent)}] [/hash
{sha256|sha-256|sha512|sha-512|whirlpool|ripemd160|ripemd-160}]
[/filesystem {None|FAT|NTFS}] [/dynamic] [/force] [/silent]
Now what you were trying should go like the below. You are missing the path or the subset of the parameters.
Create a 100 MB file container using the password test and formatted using FAT:
"C:\Program Files\VeraCrypt\VeraCrypt Format.exe" /create c:\pathofthevolume\testvolume.hc /password test /hash sha512 /encryption serpent /filesystem FAT /size 100M /force
And if you want to mount that automatically, then it should go like this:
Mount a volume called testvolume.tc using the password test, as the drive letter X.
veracrypt /v testvolume.tc /l x /a /p test /e /b
Refer the source LINK for details.
Hope it helps.

NET USE command to connect to a shared folder on local LAN

I am trying to write a batch file to connect to a shared folder on my LAN.
The command reads:
net use s: \\<server add>\sharename /user:username
How do I include the password in the command as well?
I've tried:
net use s: \\<server add>\sharename /user:username password
and get an incorrect syntax error.
The syntax of this command is:
NET USE
[devicename | *] [\\computername\sharename[\volume] [password | *]]
[/USER:[domainname\]username]
[/USER:[dotted domain name\]username]
[/USER:[username#dotted domain name]
[/SMARTCARD]
[/SAVECRED]
[[/DELETE] | [/PERSISTENT:{YES | NO}]]
NET USE {devicename | *} [password | *] /HOME
NET USE [/PERSISTENT:{YES | NO}]
This is all SOHO so assume no Server on network. I am using a windows 7 client.
The error message syntax positions the password (or a *) before the /USER: option. Putting the password before the user has always seemed illogical to me, but it's always worked.

How to create a service running a .exe file on Windows 2012 Server?

I have created .exe in .net and want to use as a service, run all time on my local machine. I am using windows server 2012. how to setup a service on my local computer.
**You can use windows shell script for create service with commands **
The sc create command performs the operations of the CreateService API function.
Here's what to do ...
copy the "yourapplication.exe " to a suitable location on your
Win2012 server (e.g. C:\Windows\System32\ ).
Use "sc " to create a new service that launches "srvany " (e.g. sc
create "Servicename" binPath= "C:'Windows'System32'srvany.exe"
DisplayName= "My Custom Service" )
Using RegEdit : create a "Parameters " key for your service (e.g.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Servicename\Paramaters)
Using RegEdit : within the newly created "Parameters " key , create
a string value called "Application " and enter the full path to the
application you are wanting to run as a service. (No quotes
required.)
Syntax:-
sc [] create [] [type= {own | share | kernel | filesys | rec | interact type= {own | share}}] [start= {boot | system | auto | demand | disabled}] [error= {normal | severe | critical | ignore}] [binpath= ] [group= ] [tag= {yes | no}] [depend= ] [obj= { | }] [displayname= ] [password= ]
More...
You can just do that too, it seems to work well too.
sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"
You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.
You can use PowerShell.
New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
Refer - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

Resources