從 PID 取得服務名稱(powershell)

從 PID 取得服務名稱(powershell)

我在解決一個小問題時遇到困難。因此,對於進程,我可以使用以下行從其 $PID 儲存其名稱:

$process_name=get-Process -id $PID |select -expand 名稱

但是,我想將該過程作為服務。我想完成相同的操作,即:將服務的名稱例如[service_name].exe儲存到變數$service_name中。

這樣做的原因是因為我只想擁有一個 .ps1 文件,然後我可以將其轉換為使用自己的 .exe.config 文件的多個服務。這樣,只需一個 .ps1 檔案就可以多次編譯為服務,例如

[服務1.exe,服務2.exe,服務3.exe,...]

每個服務都使用其對應的 .exe.config 文件,例如

[service1.exe.config、service2.exe.config、service3.exe.config、...]

有沒有辦法用powershell來做到這一點?

答案1

您可以從Processid取得服務信息

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

答案2

使用 Get-WmiObject 您可以收集可執行檔:

(Get-WmiObject win32_service | Where-Object -Property Name -Like *wallet*).PathName

此範例將顯示可執行檔名稱以及任何開關。如果你想將其捕獲到變數中,請嘗試:

$proc_name = (Get-WmiObject win32_service | Where-Object -Property Name -Like *wallet*).PathName

如果您需要任何擴展的屬性信息,請嘗試:

Get-WmiObject win32_service | ?{$_.Name -like '*wallet*'} | Select-Object -Property *

答案3

這是另一種方式 - 上面的那些可能更可靠?

$id = 5556
# (debugging) Nice little table to make sure you've got the right thing...
Get-Process | Where-Object Id -EQ $id | Select ProcessName,Id | Format-Table    
 
# Finally just hand me back the name proper
Get-Process | Where-Object Id -EQ $id | Select -Expand ProcessName 
# Depending on what you're doing with it...
# Stop-Process -Id $id

相關內容