November PowerShell One-liner

[This month’s SAPIEN newsletter offered this one liner I thought I’d share with the rest of you].

The following one line PowerShell expression should show you who is logged on to a specific server and desktop and for how long. Most logon sessions use a single instance of Explorer.exe, although it is possible for a user to manually start additional instances of Explorer.exe.

Get-WmiObject win32_process -filter "name='explorer.exe'" -computer "SERVER01"  |
select @{name="Computer";Expression={$_.CSNAME}},@{Name="Owner";Expression={
"{0}\{1}" -f $_.getOwner().Domain,$_.getOwner().User}},
@{name="Started";Expression={$_.ConvertToDateTime($_.creationdate)}},
@{name="Duration";Expression={
$started=$_.ConvertToDateTime($_.creationdate)
$now=Get-Date
($now-$started).toString()}},
@{name="KernelModeTime(s)";Expression={$_.KernelModeTime/10000000}},
@{name="UserModeTime(s)";Expression={$_.UserModeTime/10000000}}

This should give you output like this:

Computer          : SERVER01
Owner             : MyCompany\Jeff
Started           : 10/20/2008 9:01:38 AM
Duration          : 1.05:47:58.8702700
KernelModeTime(s) : 123.8179937
UserModeTime(s)   : 51.9795332


The KernelMode and UserMode times are in seconds. Because this is an object, you can pipe it to other cmdlets to sort, filter, export or convert. If you have comments or questions about this or anything else PowerShell, please visit the forums at ScriptingAnswers.com.

Download this code.