How to get process id by its service name with a script to variable

前端 未结 6 1347
闹比i
闹比i 2021-01-01 13:37

I have service named WinDefend and it runs on process svchost.exe
There other many svchost.exe processes and I need to find a way

6条回答
  •  自闭症患者
    2021-01-01 14:27

    Annoying as this is, it requires you to set a unique title for your script if you want the pid for the current process. Then search for that unique title within the list of processes. Thankfully, the Title command allows you to do just that. Also see MagicAndi's response...

    Here is my batch file solution:

    @ECHO OFF
    :SetVars
        SET _Thread=%1
        title=ExecBatch_%_Thread%
        Set /A "_iPID=0"
    :Main
        CALL :getPID _iPID %_Thread%
        ...
    EXIT /b
    
    ::----------------
    ::---- GetPID ---- 
    ::----------------
    :getPID 
        setlocal   
            set _getPIDcmd=tasklist /v /fo csv 
            for /f "tokens=2 delims=," %%i in ('%_getPIDcmd% ^| findstr /i "ExecBatch_%2"') do (
                echo %%~i
                set _pid=%%~i
            )
        endlocal & Set %~1=%_pid%
    exit /b
    

    BTW, I've had the 'pleasure' of doing this time and time again over the years, via API, or batch, or ps. Pick your poison - on a Windows platform it's all the same.

    I found an even better way via powershell: $pid returns the current process' process id.

提交回复
热议问题