PID からサービス名を取得する (PowerShell)

PID からサービス名を取得する (PowerShell)

ちょっとした問題を解決するのに苦労しています。プロセスの場合、次の行を使用して $PID から名前を保存できます。

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

しかし、私はプロセスをサービス同じ操作、つまりサービス名 (例: [service_name].exe) を変数 $service_name に格納する操作を実行したいのです。

その理由は、.ps1 ファイルを 1 つだけ用意して、それを独自の .exe.config ファイルを使用する複数のサービスに変換したいからです。1 つの .ps1 ファイルを複数回コンパイルして、次のようなサービスを作成できます。

[service1.exe、service2.exe、service3.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

関連情報