none
How to detect when My Computer Is Idle? RRS feed

  • Question

  • Hey scripting guy,

    How can i detect when My Computer Is Idle? I need to be able to run a script when my computer is idle.

    The script will write to txt file state\date\time - for example: '"Idle state 04/27/2017 22:09:43.76".

    Idle  state will occur when if there is no keyboard or mouse input during 15 min interval or other activity is occurs which doesn't required use of mouse\keyboard (such as utility running in background)

    Can you please tell me how to do it?

    Thanks a lot

    • Moved by Bill_Stewart Friday, January 26, 2018 3:29 PM This is not "scripts on demand"
    Sunday, December 10, 2017 6:36 PM

All replies

  • There is no scripting method that can do what you ask.   It can be done with the low-level API.  You can also schedule a task that run "when idle".


    \_(ツ)_/

    Sunday, December 10, 2017 7:06 PM
  • You need to use the Win32 API GetLastInputInfo. Since the return parameter is a struct, I believe you have to resort to some C# inline code - so still possible with Powershell.

    The following code is from a thread on Stackoverflow (https://stackoverflow.com/questions/15845508/get-idle-time-of-machine):

    Add-Type @'
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    namespace PInvoke.Win32 {
    
        public static class UserInput {
    
            [DllImport("user32.dll", SetLastError=false)]
            private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
    
            [StructLayout(LayoutKind.Sequential)]
            private struct LASTINPUTINFO {
                public uint cbSize;
                public int dwTime;
            }
    
            public static DateTime LastInput {
                get {
                    DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
                    DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
                    return lastInput;
                }
            }
    
            public static TimeSpan IdleTime {
                get {
                    return DateTime.UtcNow.Subtract(LastInput);
                }
            }
    
            public static int LastInputTicks {
                get {
                    LASTINPUTINFO lii = new LASTINPUTINFO();
                    lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
                    GetLastInputInfo(ref lii);
                    return lii.dwTime;
                }
            }
        }
    }
    '@
    
    for ( $i = 0; $i -lt 10; $i++ ) {
        Write-Host ("Last input " + [PInvoke.Win32.UserInput]::LastInput)
        Write-Host ("Idle for " + [PInvoke.Win32.UserInput]::IdleTime)
        Start-Sleep -Seconds (Get-Random -Minimum 1 -Maximum 5)
    }

    Wednesday, December 13, 2017 9:29 AM