August 27, 2015

PowerShell - Processes

Processes can be controlled directly by the objects and methods of the .NET framework.

You can launch any executable program in a directory named in the PATH environment variable simply by typing its name:

notepad
regedit
explorer

PowerShell can't directly access these processes once they've started. Direct control of a process is only possible if you start the process using the Start() .NET method, which enables you to check whether a process still responds or is terminated. You can also stop running process:
$process = [System.Diagnostics.Process]::Start("notepad")
$process.Responding
True
$process.HasExited
False
$process.Kill()

To view all properties, send the result to a formatting cmdlet like Format-List and append with an asterisk:
Get-Process powershell | Format-List *

If you want to rectreive processes that have been running for less than 60 minutes, you could find them like this:
Get-Process | Where-Object { $_.StartTime -gt (Get-Date).AddMinutes(-60) } | Format-Table

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName               
-------  ------    -----      ----- -----   ------     -- -----------               
    129      11     4656      11516 ...40     0.06   6416 conhost                   
    161      12     2212      14004 ...29     0.33   6440 InstallAgent              
    128      10     1644      10068 ...54     0.81   8068 notepad                   
    550      30    80468      92368 ...91     1.41   4852 powershell                

If you want to display time elapsed since the process started, then you can add a property to Format-Table with expression like this:

Get-Process | Where-Object { $_.StartTime -gt (Get-Date).AddMinutes(-60) } | Format-Table Name, Id, StartTime, @{expression={ [int](New-TimeSpan $_.StartTime (get-date) ).TotalMinutes }; label="Minutes" } -autosize

Name             Id         StartTime                         Minutes
----                 --          ---------                             -------
conhost          6416    27-Aug-15 2:57:24 PM         5
InstallAgent    6440    27-Aug-15 2:52:34 PM        10
notepad         8068    27-Aug-15 2:57:33 PM          5
powershell     4852    27-Aug-15 2:57:24 PM          5

Since Get-Process is an array you can count the rows easily.
 @(Get-Process notepad).Count

Each Process object contains methods and properties, some of the properties may be read as well as modified, and methods can be executed like commands. For example, you can set the priority of a process. This statement lowers the priority of all Notepads:

Get-Process notepad | ForEach-Object { $_.PriorityClass = "BelowNormal" }

You can stop a process by specifing its name.
Stop-Process -name Notepad

References:
http://powershell.com/cs/blogs/ebookv2/archive/2012/03/24/chapter-17-processes-services-and-event-logs.aspx

No comments:

Post a Comment