I'm looking for a way to determine the idle time of a Windows computer, specifically the last time the mouse or keyboard was active. I'd like to be able to run this command from Dameware, even when the computer is locked using Win + L. Can anyone provide the PowerShell command to achieve this?
4 Answers
Last time, I just called some C# code from within PowerShell to get the idle time, which worked fine for me.
Using LastInputInfo is probably the simplest method. You could either script it out in PowerShell or create a small C# application. Also, remember to check your local laws if you plan to store this data!
You can use PowerShell with some C# code to get the idle time. Here's a snippet you can try:
```powershell
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class IdleTime {
[DllImport("user32.dll")]
public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public struct LASTINPUTINFO {
public uint cbSize;
public uint dwTime;
}
public static uint GetIdleTime() {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lii);
GetLastInputInfo(ref lii);
return ((uint)Environment.TickCount - lii.dwTime);
}
}
"@
# Idle time in seconds
[math]::Round(([IdleTime]::GetIdleTime() / 1000),2)
```
This will give you the idle time in seconds.
For a straightforward solution, you can use the command `quser`. This will show you the idle and logon times of all users logged in, and it works well for remote sessions too!

Make sure to format your code with code blocks when sharing—it's way easier to read!