Windows – Get service name from it’s PID (powershell)

powershellwindows

I am having trouble solving a minor issue. So for processes, I can store its name from its $PID using the following line:

$process_name=get-Process -id $PID |select -expand name

However, I want to run the process as a service. I want to complete the same operation, that is: store the service's name e.g. [service_name].exe into a variable $service_name.

The reason for this is because I want to have just one .ps1 file, that I can then turn into multiple services that uses its own .exe.config files. So that just one .ps1 file can be compiled multiple times into services such as

[service1.exe, service2.exe, service3.exe, …]

and each service uses its corresponding .exe.config file such as

[service1.exe.config, service2.exe.config, service3.exe.config, …]

Is there any way to do this with powershell?

Best Answer

You can get the Service Information from Processid

(Get-WmiObject Win32_Service -Filter "ProcessId='$PID'")
Related Question