I need to know which service has executed a script, to powershell

53 Views Asked by At

I need to know which service has executed a script from the same script.

For example The service service_Test executed the test script. From the test script I want to know which service has executed it.

I have not found a way to do this, I can only see which services are running.

2

There are 2 best solutions below

0
mklement0 On

It looks like what you're asking is how to determine the path of the executable that launched the current PowerShell process, so you can compare it to your service executable path.

You can do this with a combination of Get-Process and Get-CimInstance with the Win32_Process WMI class, using the automatic $PID variable to get the current process' ID:

$parentExecutablePath = 
  (Get-Process -Id `
    (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId
  ).Path

In PowerShell (Core) 7+, the solution can be simplified, given that PowerShell now decorates the System.Diagnostics.Process instances output by Get-Process with a .Parent property:

# PS v7+ - also works on Unix-like platforms.
$parentExecutablePath =
  (Get-Process -Id $PID).Parent.Path

Not only is this simpler and shorter, it also works on Unix-like platforms.

0
Toni On

I Resolved with>

$service_cmd = get-Process -id $PID |select -expand name
write-output $service_cmd
$service_pid = $PID
write-output $service_pid
$contp = 1

while (($service_cmd -ne "dsmcsvc") -and ($contp -le 5)){
    $service_pid = (Get-CimInstance -Class Win32_Process -Filter "ProcessId = $service_pid").ParentProcessId
    write-output $service_pid
    $service_cmd = get-Process -id $service_pid |select -expand name
    $contp += 1
}
$service_name = (Get-WmiObject Win32_Service -Filter "ProcessId=$service_pid").Name

Regards