1

I want to monitor python scripts in powershell. For that I am using Get-ProcessByName. I want to monitor individual python and JAVA scripts running and store its processId in a csv file according to individual script running. Get-ProcessByName lists all the the python or JAVA processes in the same row. How do I separate all the script names in different rows. What I am currently doing is-

$process = [System.Diagnostics.Process]
$outputTime = $process::GetProcessesByName($processName.ProcessName)[0].TotalProcessorTime.TotalMilliseconds
$name = ($process::GetProcessesByName($processName.ProcessName)[0]) | Select-Object -ExpandProperty ProcessName
$extra = Get-WmiObject -Class Win32_Process -Filter "name = '$name.exe'" | Select-Object -ExpandProperty CommandLine

Here in $extra I am getting names of all the python scripts.How do I seperate all the scripts

4

2 回答 2

2

From my understanding Win32_Process already has all the information you need. You can use Select-Object and Calculated Properties to modify if required.

Get-WmiObject -Class Win32_Process |
    Where-Object {$_.Name -eq 'python.exe'} | 
    Select-Object -Property Name, 
        @{Name         = 'Script'
          Expression   = {$_.CommandLine -replace 
                          '(.*)\\(?<py>.*\.py)|(.*)\ (?<py>.*\.py.*)', 
                          '${py}'}
        }, 
        @{
            Name       = 'CpuTime'
            Expression = {($_.KernalModeTime + $_.UserModeTime) / 10000000} 
        } | 
    Sort-Object -Property CpuTime -Descending

This would output something like

    Name       Script                 CpuTime
    ----       ------                 -------
    python.exe completion.py preview  1,65625
    python.exe Untitled-1.py         0,015625

Of course this would work for java.exe or other, even multiple processes, as well. If you dont want to output the full CommandLine replace the first Calculated Property with CommandLine.

于 2018-02-12T21:03:59.980 回答
0

I would use this

Get-Process | where ProcessName -Match python
于 2018-02-12T19:24:52.537 回答