LoginSignup
1
3

More than 5 years have passed since last update.

WindowsでプロセスIDを取得する

Last updated at Posted at 2018-10-22

概要

WindowsでプロセスIDを取得する方法を記載する。

コードサンプルのとおり、
現在はPowershellで実装するのがベスト。
Batchにて取得しなければならない場合は、tasklistから取得する。

コードサンプル

10桁にゼロパディングしたプロセスIDを取得する。

Powershell


function Get-ProcessId(){
    $processId = Get-WmiObject win32_process -filter processid=$pid | ForEach-Object{$_.parentprocessid;}
    return $processId.ToString("0000000000")
}

Batch

Windowタイトルからプロセスを特定して取得するサブルーチン。
(※)パディングのため、遅延環境変数を使用している。

:GetProcessId
    setlocal enabledelayedExpansion
    set title=myname
    title %title%

    for /f "tokens=2 delims=, usebackq" %%i in (`tasklist /v /nh /fo csv /fi "IMAGENAME eq cmd.exe" ^| findstr /r *%title%*`) do ( set tmppid=0000000000%%~i) 

    set tmppid=!tmppid:~-10!
    endlocal && set pid=%tmppid% 

    exit /b %errorlevel%
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3