Weekend Scripter: Use PowerShell to Display Process Name and Uptime

Doctor Scripto

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a custom table that displays the process name and uptime.

Microsoft Scripting Guy, Ed Wilson, is here. Sometimes it seems as if the Scripting Neighbors are crazy. Yep, it is early on a Saturday morning, and at least one of my neighbors is outside mowing the grass. Dude, it is not even June yet—what’s up with that? Oh well, their lawn mower makes a cheap alarm clock. I guess that is what neighbors are for—even Scripting Neighbors. So, while I am making a pot of tea, and wondering how long the neighbors have been up, I also begin to wonder how long certain applications on the computer have been up. So I slide over to the Scripting Wife’s computer and begin to play.

Find all processes that return a process start time

I use the Get-Process cmdlet to return all processes, and I pipe the results to the Where-Object. Then I look for the existence of StartTime. I select only the name and StartTime because that is what I am interested in seeing. The command is shown here.

gps | ? starttime | select name, starttime

Create a time span

Now I need to create a TimeSpan object. I can do this by using the New-TimeSpan cmdlet. In the following command, I practice with the Notepad process, while I figure out how to best display the newly created TimeSpan.

PS C:\> (New-TimeSpan -start (gps notepad).starttime).tostring(“g”)


I finally decide that rather than creating a custom TimeSpan format, I will use a standard TimeSpan format. The standard TimeSpan format strings are documented on MSDN: Standard TimeSpan Format Strings. Using a standard TimeSpan format makes the process a lot simpler.

Create a custom table

Now that I know how to create the formatting I need for my time span, it is time to create a custom table. The trick here is to use a hash table to specify the custom property for the Format-Table cmdlet. Here is the hash table I use:

@{LABEL=’uptime’;EXPRESSION={(New-TimeSpan -start ($_.StartTime).tostring(“g”))}} -AutoSize

The entire command is shown here. This is a single-line command that wraps over three lines in my Windows PowerShell console.

gps |

? starttime |

 select name, starttime |

sort starttime -descending|

Format-Table name,

@{LABEL=’uptime’;EXPRESSION={(New-TimeSpan -start ($_.StartTime).tostring(“g”))}} -AutoSize

The command and the associated output are shown in the following image.

Image of command output

That is it for today. Join me tomorrow for a guest blog about the Windows PowerShell community by the Scripting Wife.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


Discussion is closed.

Feedback usabilla icon